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?

  • Can you create a user in your test that has no access to the object then runAs that use?
    – Eric
    Apr 24, 2019 at 4:25

1 Answer 1


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.

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;

            Boolean canQuery = MyObjectHelper.canQueryObject(...);

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .