使用 testSetup

你可以使用 @testSetup 註釋的方法編寫將在每次測試執行之前執行的程式碼:

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');
  }
}