Unit Testing

The Arrange, Act and Assert (AAA) Pattern

The AAA (Arrange-Act-Assert) pattern has become almost a standard across the industry. It suggests that you should divide your test method into three sections: arrange, act and assert. Each one of them only responsible for the part in which they are named after.

@isTest
public static void methodName_StateUnderTest_ExpectedBehavior() {
    
    // arrange
    Account person = AccountTestDataFactory.createAccount();
    AccountService service = new AccountService();
    Boolean expected = false;
    
    // act
    Test.startTest();
    Boolean actual = service.doSomething(account);
    Test.stopTest();
    
    // assert
    System.assertEquals(expected, actual);   
}

Test Method Naming

Use the following test method naming methodName_stateUnderTest_expectedBehavior

@isTest
public static void isAdult_ageLessThan18_false() {

}

@isTest
public static void withdrawMoney_invalidAccount_exceptionThrown() {

}

@isTest
public static void admitStudent_missingMandatoryFields_failToAdmit() {

}

Test Coverage vs Code Coverage

Focus on testing the code functions correctly rather than getting greater than 75% coverage

Test Data Factories

Create a TestDataFactory class per object, and insert the object and return the Id

@isTest

public without sharing class AccountTestDataFactory {

    public static Id create() {
    
        Account company = new Account();
        company.Name = 'Acme Inc';
        
        insert company
        return company.Id;
    }
    
    public static Set<Id> createMultiple() {
    
    }
}

By having a single TestDataFactory per object, we avoid very large general classes which caused issues when merging.

Last updated