Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Apex Stub API with Static Methods
public with sharing class CMTService {
public List<CMTWrapper> getCMTs() {
List<CMTWrapper> cmtWrappers = new List<CMTWrapper>();
List<CMT__mdt> cmts = [SELECT Example_Field_1__c, Example_Field_2_c FROM CMT__mdt];
for(CMT__mdt c : cmts) {
CMTWrapper cmtWrapper = new CMTWrapper(c.Example_Field_1__c, c.Example_Field_2__c);
return cmtWrappers;
public class CMTWrapper {
public String exampleField1;
public String exampleField2;
public CMTWrapper(String exampleField1, String exampleField2) {
this.exampleField1 = exampleField1;
this.exampleField2 = exampleField2;
public with sharing class ExampleController {
public static CMTService cmtService = (CMTService) di_Injector.Org.getInstance(CMTService.class);
public ExampleController(ApexPage.StandardController ctrl) {
//Usual constructor setup stuff. Setting Ids, etc.
public static Map<String, Object> doStuffThatNeedsCMTs() {
Map<String, Object> response = new Map<String, Object>();
List<CMTService.CMTWrapper> cmts = cmtService.getCMTs();
//Do stuff that needs CMTs
response.put('result', resultFromWorkWithCMTs);
return response;
private class ExampleControllerTest {
static testmethod void testDoStuff {
List<CMTService.CMTWrapper> cmtWrappers = new List<CMTService.CMTWrapper>();
CMTService.CMTWrapper exampleCMT1 = new CMTService.CMTWrapper(
CMTService.CMTWrapper exampleCMT2 = new CMTService.CMTWrapper(
di_Injector.Org.Bindings.set(new di_Module()
.bind(CMTService.class).toObject(Test.createStub(CMTService.class, new CMTServiceMock(cmtWrappers));
ExampleController.cmtService = mockService;
//Asserts goes here
public class CMTServiceMock implements System.StubProvider {
public List<CMTService.CMTWrapper> cmtWrappers = new List<CMTService.CMTWrapper>();
public CMTServiceMock(List<CMTService.CMTWrapper> cmtWrappers) {
this.cmtWrappers = cmtWrappers;
public Object handleMethodCall(Object stubbedObject, String stubbedMethodName,
Type returnType, List<Type> listOfParamTypes, List<String> listOfParamNames,
List<Object> listOfArgs) {
if(stubbedMethodName == 'getCMTs') {
return cmtWrappers;
} else {
return null;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.