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