Let’s create our test data factory for the given ContactTrigger test class; follow these steps:
Step 1: Create the new class ContactFactory in your Developer Console.
@isTest
public class ContactFactory {
public static Contact createContact(String firstName, String lastName) {
Contact newContact = new Contact();
newContact.FirstName = firstName;
newContact.LastName = lastName;
return newContact;
}
}
Step 2: Modify our already created test class for the ContactTrigger, to use the methods from the ContactFactory class for test data creation.
@isTest
private class TestContactTrigger {
@isTest
static void testContactTriggerWithSystemEquals() {
Contact testContact = ContactFactory.createContact(‘Max’, ‘Blank’); insert testContact;
Contact insertedContact = [SELECT Id, FirstName, LastName FROM Contact WHERE Id = :testContact.Id];
System.assertEquals(‘Max’, insertedContact.FirstName, ‘FirstName should be set to “Max”.’); System.assertEquals(‘Blank’, insertedContact.LastName, ‘LastName should be set to “Blank”.’);
}
@isTest
static void testContactTriggerWithSystemAssertNotEquals() {
Contact testContact = ContactFactory.createContact(‘Max’, ‘Blank’); insert testContact;
Contact insertedContact = [SELECT Id, FirstName, LastName FROM Contact WHERE Id = :testContact.Id];
System.assertNotEquals(‘Unexpected Value’, insertedContact.FirstName, ‘FirstName should not be “Unexpected Value”.’); System.assertNotEquals(‘Unexpected Value’, insertedContact.LastName, ‘LastName should not be “Unexpected Value”.’);
}
@isTest
static void testContactTriggerWithSystemAssert() {
Contact testContact = ContactFactory.createContact(‘Max’, ‘Blank’); insert testContact;
Contact insertedContact = [SELECT Id, FirstName, LastName FROM Contact WHERE Id = :testContact.Id];
System.assert(insertedContact.FirstName == ‘Max’, ‘FirstName should be set to “Max”.’); System.assert(insertedContact.LastName == ‘Blank’, ‘LastName should be set to “Blank”.’);
}
}
In the provided example, the purpose of the ContactFactory is to encapsulate the logic of creating a new Contact instance with specified firstName and lastName values. The factory class simplifies the process of creating test data, making the test code more modular and readable.
You can run the test again in Developer Console as already described in our first test example and check the test results.
The @TestSetup annotation in Apex is used to designate a method as a test setup method. A test setup method is responsible for creating test data that is shared across multiple test methods within the same test class. It helps to reduce duplication and improve the efficiency of test code.
When a test class has a test setup method, it runs once before any test methods in the class. The test setup method is used to create the required data for the test methods to run successfully. It is especially useful when you have multiple test methods that require the same set of data.