Last active
July 22, 2021 21:09
-
-
Save gitmatheus/285e7826f302f24e73f55843f4239ddd to your computer and use it in GitHub Desktop.
Mock relationships in Apex - 05 of 05
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@isTest | |
private class DataLayerHandler_Test { | |
private static MockDataLayer dataLayer; | |
private static DataLayerHandler testedClass; | |
static { | |
dataLayer = new MockDataLayer(); | |
} | |
@isTest | |
private static void proccessDocumentsTest() { | |
// consider using a Mock Data Factory, but for this example, let's create a test Account: | |
Account testAccount = new Account( | |
Name = 'TestAccount', | |
Id = getFakeId(Schema.Account.SObjectType), | |
Business__c = getFakeId(Schema.Business__c.SObjectType) | |
); | |
dataLayer.documentAccounts.add(testAccount); | |
Document__c testDocument = new Document__c( | |
Name = 'TestDocument', | |
Id = getFakeId(Schema.Document__c.SObjectType), | |
Account__r = testAccount | |
); | |
dataLayer.mockDocuments.add(testDocument); | |
// Now, all you need to do is to create a new instance of you handler class, but now, passing your mock data layer to the constructor! | |
// Since the Interface structure is the same, the mock version is accepted by the class constructor. | |
Test.startTest(); | |
testedClass = new DataLayerHandler(dataLayer); | |
testedClass.proccessDocuments(); | |
Test.stopTest(); | |
//You can even use the Mock Repository to store the result of the method proccessDocuments(), to pass to your assertions. | |
} | |
//Method to generate a fake Id based on the SObject Type: | |
public static String getFakeId(Schema.SObjectType type) { | |
String result = String.valueOf(fakeIdCounter++); | |
return type.getDescribe().getKeyPrefix() + '0'.repeat(12 - result.length()) + result; | |
} | |
public class MockDataLayer implements DataLayerHandler.IDataLayer { | |
List<Account> documentAccounts = new List<Account>(); | |
List<Document__c> mockDocuments = new List<Document__c>(); | |
List<Document__c> getDocumentList(){ | |
return mockDocuments; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment