Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Salesforce Service Locator
public class CMN_ServiceLocator {
private static final Map<Type, Type> customTypesMap = new Map<Type, Type> {
CMN_IDatabase.class => CMN_Database.class
};
private static Map<Type, Type> testTypesMap = new Map<Type, Type> {
// Mocks
};
private static Map<Type, Object> mocks = new Map<Type, Object> {
// Mocks
};
private static final Map<Type, Object> typeToInstance = new Map<Type, Object>();
public static Type resolve(Type theType) {
if (testTypesMap.containsKey(theType)) {
return testTypesMap.get(theType);
}
if (customTypesMap.containsKey(theType)) {
return customTypesMap.get(theType);
}
return theType;
}
public static Object instance(Type t) {
if (mocks.containsKey(t)) {
return mocks.get(t);
}
Type resolved = resolve(t);
if (!typeToInstance.containsKey(resolved)) {
typeToInstance.put(resolved, resolved.newInstance());
}
return typeToInstance.get(resolved);
}
@TestVisible
private static void setMock(Type originalType, Type mockType) {
testTypesMap.put(originalType, mockType);
}
@TestVisible
private static void setMock(Type originalType, Object mock) {
mocks.put(originalType, mock);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment