Test setup methods are defined in a test class, take no arguments, and return no value. The following is the syntax of a test setup method.
@testSetup static void methodName() {
}
Example
The following example shows how to create test records once and then access them in multiple test methods. Also, the example shows how changes that are made in the first test method are rolled back and are not available to the second test method.
@isTest
private class CommonTestSetup {
@testSetup static void setup() {
// Create common test accounts
List<Account> testAccts = new List<Account>();
for(Integer i=0;i<2;i++) {
testAccts.add(new Account(Name = 'TestAcct'+i));
}
insert testAccts;
}
@isTest static void testMethod1() {
// Get the first test account by using a SOQL query
Account acct = [SELECT Id FROM Account WHERE Name='TestAcct0' LIMIT 1];
// Modify first account
acct.Phone = '555-1212';
// This update is local to this test method only.
update acct;
// Delete second account
Account acct2 = [SELECT Id FROM Account WHERE Name='TestAcct1' LIMIT 1];
// This deletion is local to this test method only.
delete acct2;
// Perform some testing
}
@isTest static void testMethod2() {
// The changes made by testMethod1() are rolled back and
// are not visible to this test method.
// Get the first account by using a SOQL query
Account acct = [SELECT Phone FROM Account WHERE Name='TestAcct0' LIMIT 1];
// Verify that test account created by test setup method is unaltered.
System.assertEquals(null, acct.Phone);
// Get the second account by using a SOQL query
Account acct2 = [SELECT Id FROM Account WHERE Name='TestAcct1' LIMIT 1];
// Verify test account created by test setup method is unaltered.
System.assertNotEquals(null, acct2);
// Perform some testing
}
}
Test Setup Method Considerations
Test setup methods are supported only with the default data isolation mode for a test class. If the test class or a test method has access to organization data by using the @isTest(SeeAllData=true) annotation, test setup methods aren’t supported in this class. Because data isolation for tests is available for API versions 24.0 and later, test setup methods are also available for those versions only.
Multiple test setup methods are allowed in a test class, but the order in which they’re executed by the testing framework isn’t guaranteed.
If a fatal error occurs during the execution of a test setup method, such as an exception that’s caused by a DML operation or an assertion failure, the entire test class fails, and no further tests in the class are executed.
If a test setup method calls a non-test method of another class, no code coverage is calculated for the non-test method.
No comments:
Post a Comment