Skip to content

Instantly share code, notes, and snippets.

@afawcett
Forked from madmax983/CMTService.cls
Last active August 17, 2018 23:53
Show Gist options
  • Save afawcett/3fd60744fe7263d7dcf3d5db0d338a67 to your computer and use it in GitHub Desktop.
Save afawcett/3fd60744fe7263d7dcf3d5db0d338a67 to your computer and use it in GitHub Desktop.
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);
cmtWrappers.add(cmtWrapper);
}
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.
}
@RemoteAction
@AuraEnabled
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;
}
}
@isTest
private class ExampleControllerTest {
static testmethod void testDoStuff {
List<CMTService.CMTWrapper> cmtWrappers = new List<CMTService.CMTWrapper>();
CMTService.CMTWrapper exampleCMT1 = new CMTService.CMTWrapper(
'Config1',
'Config2'
);
cmtWrappers.add(exampleCMT1);
CMTService.CMTWrapper exampleCMT2 = new CMTService.CMTWrapper(
'Config3',
'Config4'
);
cmtWrappers.add(exampleCMT2);
di_Injector.Org.Bindings.set(new di_Module()
.bind(CMTService.class).toObject(Test.createStub(CMTService.class, new CMTServiceMock(cmtWrappers));
ExampleController.cmtService = mockService;
Test.startTest();
ExampleController.doStuffThatNeedsCMTs();
Test.stopTest();
//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