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

What do you call an IPA symbol that lacks a name (e.g. ɲ)?

Processing ADC conversion result: DMA vs Processor Registers

What is /etc/mtab in Linux?

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

false 'Security alert' from Google - every login generates mails from 'no-reply@accounts.google.com'

Simulate round-robin tournament draw

Show two Lagrangians are equivalent

Why did Israel vote against lifting the American embargo on Cuba?

Married in secret, can marital status in passport be changed at a later date?

What were wait-states, and why was it only an issue for PCs?

Like totally amazing interchangeable sister outfit accessory swapping or whatever

What's the difference between using dependency injection with a container and using a service locator?

How can I wire a 9-position switch so that each position turns on one more LED than the one before?

Determinant of a matrix with 2 equal rows

/bin/ls sorts differently than just ls

In search of the origins of term censor, I hit a dead end stuck with the greek term, to censor, λογοκρίνω

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

Why doesn't the university give past final exams' answers?

When does Bran Stark remember Jamie pushing him?

What happened to Viserion in Season 7?

Deciphering death certificate writing

Why is water being consumed when my shutoff valve is closed?

Is a self contained air-bullet cartridge feasible?

Cisco DHCP Router



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;








1















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






























    1















    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


























      1












      1








      1








      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

      1488




      1488




















          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

                    Era Viking Índice Início da Era Viquingue | Cotidiano | Sociedade | Língua | Religião | A arte | As primeiras cidades | As viagens dos viquingues | Viquingues do Oeste e Leste | Fim da Era Viquingue | Fontes históricas | Referências Bibliografia | Ligações externas | Menu de navegação«Sverige då!»«Handel I vikingetid»«O que é Nórdico Antigo»Mito, magia e religião na volsunga saga Um olhar sobre a trajetória mítica do herói sigurd«Bonden var den verklige vikingen»«Vikingatiden»«Vikingatiden»«Vinland»«Guerreiras de Óðinn: As Valkyrjor na Mitologia Viking»1519-9053«Esculpindo símbolos e seres: A arte viking em pedras rúnicas»1679-9313Historia - Tema: VikingarnaAventura e Magia no Mundo das Sagas IslandesasEra Vikinge

                    What's the metal clinking sound at the end of credits in Avengers: Endgame?What makes Thanos so strong in Avengers: Endgame?Who is the character that appears at the end of Endgame?What happens to Mjolnir (Thor's hammer) at the end of Endgame?The People's Ages in Avengers: EndgameWhat did Nebula do in Avengers: Endgame?Messing with time in the Avengers: Endgame climaxAvengers: Endgame timelineWhat are the time-travel rules in Avengers Endgame?Why use this song in Avengers: Endgame Opening Logo Sequence?Peggy's age in Avengers Endgame

                    Are there legal definitions of ethnicities/races? The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Legal definitions in the United StatesAre there truly legal limits on US interest rates?Are gender identity and sexual orientation federally protected?Why is there an apparent legal bias against digital services?What limits are there to the powers of individual judges in the United States legal system?Are women only scholarships legal under Irish / EU law?Is the term “race” defined by Public Law enacted by Congress of the United StatesIs there a legal definition of race in the US?Neighbors are spying for landlord on Renters is it legal?Are Protected Classes Bi-directional?