Hi,
Test
setup methods can be time-saving when you need to create reference or
prerequisite data for all test methods, or a common set of records that all
test methods operate on.
We
have to use "@testSetup" annotation to write test setup method.
Small
Use Case for you:
Case
is updating with an account when case is created with different scenarios.
Then
for creating test class for the same requirement i have to create an account in
each method for covering different scenarios in the logic.
But
with "testsetup" method we can avoid creating the same account in
multiple methods instead we can create once in testsetup method then we can
utilize the same in all test methods.
Syntax:
@testSetup
static void methodName() {
}
Eg:
--
@isTest
private
class CommonTestSetup {
@testSetup static void setup() {
// Create common test accounts
Account accountObj = new Account(Name='ABCD Account');
insert accountObj;
}
@isTest static void testMethod1() {
//Create case with a scenario it can take account data from the above test method to update on case based on your original logic to cover your code
}
@isTest static void testMethod2() {
//Create case with a scenario it can take account data from the above test method to update on case based on your original logic to cover your code
}
}
Note:
If
a test class contains a test setup method, the testing framework executes the
test setup method first, before any test method in the class. Records that are
created in a test setup method are available to all test methods in the test
class and are rolled back at the end of test class execution. If a test method
changes those records,such as record field updates or record deletions, those
changes are rolled back after
each test method finishes execution. The next
executing test method gets access to the original unmodified state of those
records.