Salesforce Apex Testing Using testSetup


Example

You can use a method annotated with @testSetup to write code that will have been executed before each test run:

public class AccountService {
  public static Account fetchAccount() {
    return [ SELECT Id, Name FROM Account LIMIT 1 ];
  }
}
@isTest
public class AccountServiceTest {
  private static final String TEST_ACCOUNT_NAME = 'My Test Account';

  @testSetup
  public static void setUpAccountData() {
    Account a = new Account(Name = TEST_ACCOUNT_NAME);
  }

  @isTest
  public static void testFetchAccount() {
    Account a = AccountService.fetchAccount();
    System.assertNotEquals(null, a, 'Account should not be null');
    System.assertEquals(TEST_ACCOUNT_NAME, a.Name, 'Account name should be correct');
  }
}