Is there a way to fake a method response using Mock or Stubs?Does 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

Which big number is bigger?

Classification of surfaces

Get consecutive integer number ranges from list of int

Why does nature favour the Laplacian?

How could Tony Stark make this in Endgame?

How can Republicans who favour free markets, consistently express anger when they don't like the outcome of that choice?

Do I have an "anti-research" personality?

What happens to Mjolnir (Thor's hammer) at the end of Endgame?

How to stop co-workers from teasing me because I know Russian?

What's the name of these pliers?

How to fry ground beef so it is well-browned

What is the philosophical significance of speech acts/implicature?

Phrase for the opposite of "foolproof"

How can I practically buy stocks?

Should the Death Curse affect an undead PC in the Tomb of Annihilation adventure?

How to pronounce 'c++' in Spanish

Philosophical question on logistic regression: why isn't the optimal threshold value trained?

How do I check if a string is entirely made of the same substring?

How to write a column outside the braces in a matrix?

How do I deal with a coworker that keeps asking to make small superficial changes to a report, and it is seriously triggering my anxiety?

Can SQL Server create collisions in system generated constraint names?

How to not starve gigantic beasts

Does a large simulator bay have standard public address announcements?

How did Captain America manage to do this?



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


Does 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;








4















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
























  • Can you create a user in your test that has no access to the object then runAs that use?

    – Eric
    2 days ago

















4















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
























  • Can you create a user in your test that has no access to the object then runAs that use?

    – Eric
    2 days ago













4












4








4








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 Apr 23 at 19:42







WEFX

















asked Apr 23 at 19:22









WEFXWEFX

1699




1699












  • Can you create a user in your test that has no access to the object then runAs that use?

    – Eric
    2 days ago

















  • Can you create a user in your test that has no access to the object then runAs that use?

    – Eric
    2 days ago
















Can you create a user in your test that has no access to the object then runAs that use?

– Eric
2 days ago





Can you create a user in your test that has no access to the object then runAs that use?

– Eric
2 days ago










1 Answer
1






active

oldest

votes


















8














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









    8














    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



























      8














      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

























        8












        8








        8







        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 Apr 23 at 19:47









        Adrian LarsonAdrian Larson

        111k19122260




        111k19122260



























            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

            How does Billy Russo acquire his 'Jigsaw' mask? Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Favourite questions and answers from the 1st quarter of 2019Why does Bane wear the mask?Why does Kylo Ren wear a mask?Why did Captain America remove his mask while fighting Batroc the Leaper?How did the OA acquire her wisdom?Is Billy Breckenridge gay?How does Adrian Toomes hide his earnings from the IRS?What is the state of affairs on Nootka Sound by the end of season 1?How did Tia Dalma acquire Captain Barbossa's body?How is one “Deemed Worthy”, to acquire the Greatsword “Dawn”?How did Karen acquire the handgun?

            Личност Атрибути на личността | Литература и източници | НавигацияРаждането на личносттаредактиратередактирате

            A sequel to Domino's tragic life Why Christmas is for Friends Cold comfort at Charles' padSad farewell for Lady JanePS Most watched News videos