3

I'm using Stub API (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_stub_api.htm) to mock a class that implements Schedulable and because of this I'm getting an error. I've done my best to simplify implementation and remove all the unnecessary logic here. Please take a look at the code snippets below followed by error that I'm getting:

My main class wants to use mocks. It is something like this:

public with sharing class MainClass {
    private ClassToMock mockClass;

    // constructor that facilitates mocking
    public MainClass(ClassToMock mockedClass) {
        this.mockClass = mockedClass;
    }

    public void methodToTest() {
        this.mockClass.methodToCall();
    }
}

The class that I want to mock looks like this (note that it implements Schedulable which is giving me the issue with mocking!) :

public with sharing class ClassToMock implements Schedulable {
    public void execute(SchedulableContext ctxt) {
        // some logic
    }

    public void methodToCall() {
        // some logic
    }
}

now for the above class I have a test class in which I implement MockProvider:

@IsTest
public with sharing class ClassToMockTest {

    public class MockProvider implements System.StubProvider, System.Schedulable {
        public Object handleMethodCall(Object stubbedObject, String stubbedMethodName, Type returnType,
                List<Type> listOfParamTypes, List<String> listOfParamNames, List<Object> listOfArgs) {
            // implemented some mocking logic here
            return null;
        }

        public void execute(SchedulableContext ctxt) {
        }

    }
}

Finally I have the MocksUtils class implemented like this:

public with sharing class MocksUtils {
    private MocksUtils() {}

    public static ClassToMockTest.MockProvider getClassToMockInstance() {
        return new ClassToMockTest.MockProvider();
    }

    public static Object createMock(Type typeToMock) {
        return Test.createStub(typeToMock, MocksUtils.getClassToMockInstance());
    }
}

So the above code shows how I've setup infrastructure to be able to do a test for MainClass using Stub API. The issue is that when I want to use it in MainClassTest to do the mock, like this:

ClassToMock classMock = (ClassToMock)MocksUtils.createMock(ClassToMock.class);

I get the following error:

System.TypeException: Class ClassToMock__sfdc_ApexStub must implement the method: void System.Schedulable.execute(System.SchedulableContext)

I have done this before with no issues for normal classes but since this one is using Schedulable I'm having some issues. Anyone knows how to deal with this issues? I couldn't find anything online to explain using Stub API when there is Schedulable class involved.

0

You must log in to answer this question.

Browse other questions tagged .