Is there a way to fake a method response using Mock or Stubs? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) 2019 Community Moderator Election ResultsDoes HttpCalloutMock work when the tested method doesn't return HttpResponse?Mock class not working with Dynamic & Unique end-pointHTTP Mock Response class has 0 coverageIs there a way to create more than 50000 records in a unit test context?Mock Service .setBody()Post callout behavior assertions for unit test with static resource callout mock failBasic Mock Test Coverage HelpHow can I reference a trigger's method and/or variable from a test class?Can we mock relationships in Apex?Method Is Not Visible: APEX Trailhead Unit Testing Challenge

Is Bran literally the world's memory?

What's parked in Mil Moscow helicopter plant?

Determinant of a matrix with 2 equal rows

Did war bonds have better investment alternatives during WWII?

How do I deal with an erroneously large refund?

What's called a person who work as someone who puts products on shelves in stores?

Like totally amazing interchangeable sister outfit accessory swapping or whatever

Deciphering death certificate writing

Will I have to go through TSA security when I return to the US after preclearance?

Does using the Inspiration rules for character defects encourage My Guy Syndrome?

Is there a way to fake a method response using Mock or Stubs?

The 'gros' functor from schemes into (strictly) locally ringed topoi

Could typically electronic sounds be generated mechanically?

Why does Java have support for time zone offsets with seconds precision?

Protagonist's race is hidden - should I reveal it?

`FindRoot [ ]`::jsing: Encountered a singular Jacobian at a point...WHY

How did Elite on the NES work?

Will I be more secure with my own router behind my ISP's router?

Why these surprising proportionalities of integrals involving odd zeta values?

Variable does not exist: sObjectType (Task.sObjectType)

How would it unbalance gameplay to rule that Weapon Master allows for picking a fighting style?

Why did Europeans not widely domesticate foxes?

Not within Jobscope - Aggravated injury

Is it appropriate to mention a relatable company blog post when you're asked about the company?



Is there a way to fake a method response using Mock or Stubs?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
2019 Community Moderator Election ResultsDoes HttpCalloutMock work when the tested method doesn't return HttpResponse?Mock class not working with Dynamic & Unique end-pointHTTP Mock Response class has 0 coverageIs there a way to create more than 50000 records in a unit test context?Mock Service .setBody()Post callout behavior assertions for unit test with static resource callout mock failBasic Mock Test Coverage HelpHow can I reference a trigger's method and/or variable from a test class?Can we mock relationships in Apex?Method Is Not Visible: APEX Trailhead Unit Testing Challenge



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I have a helper method in my code called canQueryObject, and that method returns a boolean. I have some code that calls the method via the following line of code:



if(!myObjectHelper.canQueryObject(Schema.SObjectType.<<objectType>>)) ... 


I'd like to test some scenarios where the scenario is false. Is there a way I can use Mock or Stubs in a unit-test to set canQueryObject to false?










share|improve this question






























    2















    I have a helper method in my code called canQueryObject, and that method returns a boolean. I have some code that calls the method via the following line of code:



    if(!myObjectHelper.canQueryObject(Schema.SObjectType.<<objectType>>)) ... 


    I'd like to test some scenarios where the scenario is false. Is there a way I can use Mock or Stubs in a unit-test to set canQueryObject to false?










    share|improve this question


























      2












      2








      2








      I have a helper method in my code called canQueryObject, and that method returns a boolean. I have some code that calls the method via the following line of code:



      if(!myObjectHelper.canQueryObject(Schema.SObjectType.<<objectType>>)) ... 


      I'd like to test some scenarios where the scenario is false. Is there a way I can use Mock or Stubs in a unit-test to set canQueryObject to false?










      share|improve this question
















      I have a helper method in my code called canQueryObject, and that method returns a boolean. I have some code that calls the method via the following line of code:



      if(!myObjectHelper.canQueryObject(Schema.SObjectType.<<objectType>>)) ... 


      I'd like to test some scenarios where the scenario is false. Is there a way I can use Mock or Stubs in a unit-test to set canQueryObject to false?







      unit-test mock






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 1 hour ago







      WEFX

















      asked 1 hour ago









      WEFXWEFX

      1538




      1538




















          1 Answer
          1






          active

          oldest

          votes


















          4














          I typically use a fairly simple pattern and don't bring in a framework. It would look something like the following:



          public virtual with sharing class MyObjectHelper

          static MyObjectHelper instance = new MyObjectHelper();
          @TestVisible static void setMock(MyObjectHelper mock) instance = mock;

          public static Boolean canQueryObject(SObjectType sObjectType)

          return instance.getCanQueryObject(sObjectType);


          // the two method names cannot match or you will get a compile fail
          protected virtual Boolean getCanQueryObject(SObjectType sObjectType)

          return sObjectType.getDescribe().isQueryable();




          Then in your test, you can have a mock return always true or always false, as you wish.



          @IsTest
          class MyObjectHelperTests

          class HelperMock extends MyObjectHelper

          Boolean isQueryable = true;
          protected override Boolean getCanQueryObject(SObjectType sObjectType)

          return isQueryable;



          @IsTest static void testCannotQuery()

          HelperMock mock = new HelperMock();
          mock.isQueryable = false;
          MyObjectHelper.setMock(mock);

          Test.startTest();
          Boolean canQuery = MyObjectHelper.canQueryObject(...);
          Test.stopTest();

          system.assertEquals(false, canQuery, 'Some informative message');







          share|improve this answer























            Your Answer








            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "459"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f258841%2fis-there-a-way-to-fake-a-method-response-using-mock-or-stubs%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            4














            I typically use a fairly simple pattern and don't bring in a framework. It would look something like the following:



            public virtual with sharing class MyObjectHelper

            static MyObjectHelper instance = new MyObjectHelper();
            @TestVisible static void setMock(MyObjectHelper mock) instance = mock;

            public static Boolean canQueryObject(SObjectType sObjectType)

            return instance.getCanQueryObject(sObjectType);


            // the two method names cannot match or you will get a compile fail
            protected virtual Boolean getCanQueryObject(SObjectType sObjectType)

            return sObjectType.getDescribe().isQueryable();




            Then in your test, you can have a mock return always true or always false, as you wish.



            @IsTest
            class MyObjectHelperTests

            class HelperMock extends MyObjectHelper

            Boolean isQueryable = true;
            protected override Boolean getCanQueryObject(SObjectType sObjectType)

            return isQueryable;



            @IsTest static void testCannotQuery()

            HelperMock mock = new HelperMock();
            mock.isQueryable = false;
            MyObjectHelper.setMock(mock);

            Test.startTest();
            Boolean canQuery = MyObjectHelper.canQueryObject(...);
            Test.stopTest();

            system.assertEquals(false, canQuery, 'Some informative message');







            share|improve this answer



























              4














              I typically use a fairly simple pattern and don't bring in a framework. It would look something like the following:



              public virtual with sharing class MyObjectHelper

              static MyObjectHelper instance = new MyObjectHelper();
              @TestVisible static void setMock(MyObjectHelper mock) instance = mock;

              public static Boolean canQueryObject(SObjectType sObjectType)

              return instance.getCanQueryObject(sObjectType);


              // the two method names cannot match or you will get a compile fail
              protected virtual Boolean getCanQueryObject(SObjectType sObjectType)

              return sObjectType.getDescribe().isQueryable();




              Then in your test, you can have a mock return always true or always false, as you wish.



              @IsTest
              class MyObjectHelperTests

              class HelperMock extends MyObjectHelper

              Boolean isQueryable = true;
              protected override Boolean getCanQueryObject(SObjectType sObjectType)

              return isQueryable;



              @IsTest static void testCannotQuery()

              HelperMock mock = new HelperMock();
              mock.isQueryable = false;
              MyObjectHelper.setMock(mock);

              Test.startTest();
              Boolean canQuery = MyObjectHelper.canQueryObject(...);
              Test.stopTest();

              system.assertEquals(false, canQuery, 'Some informative message');







              share|improve this answer

























                4












                4








                4







                I typically use a fairly simple pattern and don't bring in a framework. It would look something like the following:



                public virtual with sharing class MyObjectHelper

                static MyObjectHelper instance = new MyObjectHelper();
                @TestVisible static void setMock(MyObjectHelper mock) instance = mock;

                public static Boolean canQueryObject(SObjectType sObjectType)

                return instance.getCanQueryObject(sObjectType);


                // the two method names cannot match or you will get a compile fail
                protected virtual Boolean getCanQueryObject(SObjectType sObjectType)

                return sObjectType.getDescribe().isQueryable();




                Then in your test, you can have a mock return always true or always false, as you wish.



                @IsTest
                class MyObjectHelperTests

                class HelperMock extends MyObjectHelper

                Boolean isQueryable = true;
                protected override Boolean getCanQueryObject(SObjectType sObjectType)

                return isQueryable;



                @IsTest static void testCannotQuery()

                HelperMock mock = new HelperMock();
                mock.isQueryable = false;
                MyObjectHelper.setMock(mock);

                Test.startTest();
                Boolean canQuery = MyObjectHelper.canQueryObject(...);
                Test.stopTest();

                system.assertEquals(false, canQuery, 'Some informative message');







                share|improve this answer













                I typically use a fairly simple pattern and don't bring in a framework. It would look something like the following:



                public virtual with sharing class MyObjectHelper

                static MyObjectHelper instance = new MyObjectHelper();
                @TestVisible static void setMock(MyObjectHelper mock) instance = mock;

                public static Boolean canQueryObject(SObjectType sObjectType)

                return instance.getCanQueryObject(sObjectType);


                // the two method names cannot match or you will get a compile fail
                protected virtual Boolean getCanQueryObject(SObjectType sObjectType)

                return sObjectType.getDescribe().isQueryable();




                Then in your test, you can have a mock return always true or always false, as you wish.



                @IsTest
                class MyObjectHelperTests

                class HelperMock extends MyObjectHelper

                Boolean isQueryable = true;
                protected override Boolean getCanQueryObject(SObjectType sObjectType)

                return isQueryable;



                @IsTest static void testCannotQuery()

                HelperMock mock = new HelperMock();
                mock.isQueryable = false;
                MyObjectHelper.setMock(mock);

                Test.startTest();
                Boolean canQuery = MyObjectHelper.canQueryObject(...);
                Test.stopTest();

                system.assertEquals(false, canQuery, 'Some informative message');








                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 1 hour ago









                Adrian LarsonAdrian Larson

                111k19121259




                111k19121259



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Salesforce Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f258841%2fis-there-a-way-to-fake-a-method-response-using-mock-or-stubs%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                    Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                    François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480