Set Up Test Data for an Entire Test Class
Use test setup
methods (methods that are annotated with @testSetup) to create test records
once and then access them in any test method in the test class. Test setup
methods are useful and can be time-saving when you need to create a common set
of records that all test methods operate on or prerequisite data.
Records created in a
test setup method are rolled back at the end of test class execution. Test
setup methods enable you to create common test data easily and efficiently. By
setting up records once for the class, you don’t need to re-create records for
each test method.
Syntax:
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:
@isTest
public class TestSetupMethodCls{
@testSetup static void TestSetupMethod(){
Account acc = new Account(Name = 'Test Acc');
insert acc;
}
static testMethod void TestAccount(){
Account acc = [Select Id, Name form Account Limit 1];
System.assertEquals('Test Acc', acc.Name);
}
}
public class TestSetupMethodCls{
@testSetup static void TestSetupMethod(){
Account acc = new Account(Name = 'Test Acc');
insert acc;
}
static testMethod void TestAccount(){
Account acc = [Select Id, Name form Account Limit 1];
System.assertEquals('Test Acc', acc.Name);
}
}
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.
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 test
methods 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