Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Real Unit Tests using ApexMocks
public class MyController{
private MyInterface myImplementation;
public Integer valueOne{get;set;}
public Integer valueTwo{get;set;}
public MyController(MyInterface myImplementation){
this.myImplementation = myImplementation;
}
public Integer calculatedTotalValue(){
return myImplementation.calculateValues(valueOne, valueTwo);
}
}
@isTest
public class MyControllerTest{
public static testMethod void testCalculateValues(){
fflib_ApexMocks mocks = new fflib_ApexMocks();
MyInterface mockMyService = new MockMyService(mocks);
mocks.startStubbing();
mocks.when(mockMyService.calculateValues(5, 3)).thenReturn(8);
mocks.stopStubbing();
Test.startTest();
MyController controller = new MyController(mockMyService);
controller.valueOne = 5;
controller.valueTwo = 3;
Integer totalValue = controller.calculatedTotalValue();
Test.stopTest();
System.assertEquals(8, totalValue, 'The service should return 8');
}
private class MockMyService implements MyInterface{
private fflib_ApexMocks mocks;
public MockMyService(fflib_ApexMocks mocks){
this.mocks = mocks;
}
public Integer calculateValues(Integer valueOne, Integer valueTwo){
if (mocks.Stubbing){
mocks.prepareMethodReturnValue(this, 'calculateValues', new List<Object> {valueOne, valueTwo});
return null;
}else{
mocks.recordMethod(this, 'calculateValues', new List<Object> {valueOne, valueTwo});
fflib_MethodReturnValue methodReturnValue = mocks.getMethodReturnValue(this, 'calculateValues', new List<Object> {valueOne, valueTwo});
if (methodReturnValue != null){
if (methodReturnValue.ReturnValue instanceof Exception)
{
throw ((Exception) methodReturnValue.ReturnValue);
}
return (Integer) methodReturnValue.ReturnValue;
}
}
return null;
}
}
}
public interface MyInterface{
Integer calculateValues(Integer valueOne, Integer valueTwo);
}
public class MyService implements MyInterface{
public Integer calculateValues(Integer valueOne, Integer valueTwo){
return valueOne + valueTwo;
}
}
Owner

jessealtman commented Jun 27, 2014

All of this code is related to the following article: Real Unit Tests using ApexMocks

Owner

jessealtman commented Jun 27, 2014

This code is further explained in: ApexMocks: How Does It Work?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment