Hello Friends ,
Today ,we are going to disuse about a useful topic for every developer :- method with @testSetup annotation
Methods defined with the @testSetup annotation are used for creating common test records that are available for all test methods in the class.
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() {
- }
Benefits
- By setting up records once for the class, you don’t need to re-create records for each test method. It’s a good time saver.
- Reduces test execution times, especially when you’re working with many records.
Example as to how to use the Test Setup method,
@isTest
private class SetupClassTest
{
@testSetup static void insertContact()
{
Contact cnt = new Contact();
cnt.LastName = ‘Arunkumar’;
cnt.Email = ‘testcontact@test.com’;
insert cnt;
}
static testMethod void updateContactEmail()
{
Contact cnt = [SELECT Name, Email FROM Contact];
System.assertEquals(cnt.Email, ‘testcontact@test.com’);
// update contact email address. This update is local to this test method only.
cnt.Email = ‘testupdated@test.com’;
update cnt;
System.assertEquals(cnt.Email, ‘testupdated@test.com’);
// Salesforce automatically rolled back to the original value.
}
static testMethod void verifyTheOriginalEmail()
{
Contact cnt = [SELECT Name, Email FROM Contact];
// verify the email original email address.
System.assertEquals(cnt.Email, ‘testcontact@test.com’);
}
}
Explanation :-
- In the above test class, we inserted the Contact record in the Test Setup Method. So the inserted contact record is accessible in all test methods within the test class.
- Test setup methods are defined in a test class, take no arguments, and return no value.
- If a test class contains a test setup method, the testing framework executes the test setup method first, before any test method is executed in the class.
Limitation
As per salesforce documentation, take a look on the below limitations before using this method,
- Test setup methods aren’t supported for @isTest (SeeAllData=true) annotation test classes. Hence, you can use this feature from the API version 24.0 or above.
- 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.