Skip to content

Instantly share code, notes, and snippets.

@jessealtman
Created June 27, 2014 19:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessealtman/c2edc7bc5f440e3fd915 to your computer and use it in GitHub Desktop.
Save jessealtman/c2edc7bc5f440e3fd915 to your computer and use it in GitHub Desktop.
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;
}
}
@jessealtman
Copy link
Author

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

@jessealtman
Copy link
Author

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