Skip to content

Instantly share code, notes, and snippets.

Created June 27, 2014 19:12
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);
public class MyControllerTest{
public static testMethod void testCalculateValues(){
fflib_ApexMocks mocks = new fflib_ApexMocks();
MyInterface mockMyService = new MockMyService(mocks);
mocks.when(mockMyService.calculateValues(5, 3)).thenReturn(8);
MyController controller = new MyController(mockMyService);
controller.valueOne = 5;
controller.valueTwo = 3;
Integer totalValue = controller.calculatedTotalValue();
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;
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;
Copy link

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