Hello Shubham,
As you know that, Initially we had to create test data in every test method, because every test method is considered a different transaction with its own governor limits. But Salesforce has introduced @TestSetUp annotation for test class method. You can write a method in test class, with @TestSetUp annotation applied, and create all your common test data in this method.
Few key points about TestSetUp methods:
- Method marked with @TestSetUp annotation executes before any testMethod.
- Data created in this method doesn’t need to be created again and again, and it is by default available for all test methods.
- There can be only one setup method per test class.
- 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.
- Test setup methods are available for 24.0 or later versions only.
- Every test method will get unchanged version of the test data created in setup method, doesn’t matter if any other test method has modified the data. I will show this in testMethod2 of below example.
@isTest
private class TestSetupMethodExample {
//Below is a method with @testsetup annotation, the name can be anything like setup(), oneTimeData(), etc.
@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() {
// Here, we will see if test data created in setup method is available or not, 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
}
}