Created
November 3, 2020 19:58
-
-
Save gbutt/f0567a2cd2c5b48813b30d696528c58c to your computer and use it in GitHub Desktop.
StubProviderImpl.cls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@IsTest | |
public class StubProviderImpl implements System.StubProvider { | |
public Type mockType {get; private set;} | |
private Map<String, Object> mockedCalls {get; set;} | |
private Map<String, Exception> mockedExceptions {get; set;} | |
private Map<String, Object[]> callLog {get; set;} | |
public StubProviderImpl(Type mockType) { | |
this.mockType = mockType; | |
this.mockedCalls = new Map<String, Object>(); | |
this.mockedExceptions = new Map<String, Exception>(); | |
this.callLog = new Map<String, Object[]>(); | |
} | |
public Object handleMethodCall(Object stubbedObject, String stubbedMethodName, Type returnType, List<Type> listOfParamTypes, List<String> listOfParamNames, List<Object> listOfArgs) { | |
recordCall(stubbedMethodName, listOfArgs); | |
return getMockCallForMethod(stubbedMethodName); | |
} | |
public void mockCall(String methodName, Object response) { | |
mockedCalls.put(methodName, response); | |
} | |
public void mockException(String methodName, Exception ex) { | |
mockedExceptions.put(methodName, ex); | |
} | |
public Object[] getLoggedCallFor(String methodName) { | |
return callLog.get(methodName); | |
} | |
private void recordCall(String methodName, Object[] args) { | |
callLog.put(methodName, args); | |
} | |
private Object getMockCallForMethod(String methodName) { | |
if (mockedExceptions.containsKey(methodName)) { | |
throw mockedExceptions.get(methodName); | |
} | |
return mockedCalls.get(methodName); | |
} | |
public Object buildMockInstance() { | |
return Test.createStub(mockType, this); | |
} | |
public Boolean wasCalled(String methodName) { | |
return callLog.containsKey(methodName); | |
} | |
public void verifyCall(String methodName, List<Object> parameters) { | |
List<Object> callParams = getLoggedCallFor(methodName); | |
System.assertEquals(parameters.size(), callParams.size()); | |
for (Integer idx = 0; idx < parameters.size(); idx++) { | |
System.assertEquals(parameters[idx], callParams[idx]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment