Development Best Practices
  • Home
  • Clean Code
  • Apex
    • Naming Conventions
    • Triggers
    • Unit Testing
    • Principles
      • KISS
      • DRY
      • Single Responsibility
      • Open/Closed
      • YAGNI
    • Patterns
    • SOQL
    • Exception Handling
    • Magic Strings
  • Lightning Components
    • Aura
    • LWC
  • Automation
    • Process Builder
  • Salesforce DX and VSCode
  • Git Source Control
    • Install Git
    • Using Git
    • Development Workflow
      • The Rules
    • Feature Branch Workflow
Powered by GitBook
On this page
  • The Arrange, Act and Assert (AAA) Pattern
  • Test Method Naming
  • Test Coverage vs Code Coverage
  • Test Data Factories
  1. Apex

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.

PreviousTriggersNextPrinciples

Last updated 5 years ago