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');
}
}