Salesforce apex test class example
- User
Salesforce apex test class example
- Assistant
Sure! Below is an example of a Salesforce Apex test class:
java
Salesforce apex test class example
Sure! Below is an example of a Salesforce Apex test class:
@isTest
public class MyTestClass {
// Method to set up test data
public static void setupTestData() {
// Create test records
Account testAccount = new Account(Name = 'Test Account');
insert testAccount;
Contact testContact = new Contact(FirstName = 'John', LastName = 'Doe', AccountId = testAccount.Id);
insert testContact;
}
// Test method for verifying the functionality
@isTest
public static void testFunctionality() {
// Set up test data
setupTestData();
// Perform actions that should be tested
// For example, querying records
List<Account> accounts = [SELECT Id, Name FROM Account];
List<Contact> contacts = [SELECT Id, FirstName, LastName FROM Contact];
// Assert the expected results
System.assertEquals(1, accounts.size());
System.assertEquals('Test Account', accounts[0].Name);
System.assertEquals(1, contacts.size());
System.assertEquals('John', contacts[0].FirstName);
System.assertEquals('Doe', contacts[0].LastName);
}
}
In this example, we have a test class named MyTestClass. It contains two methods: setupTestData() and testFunctionality().
The setupTestData() method is responsible for creating test records, in this case, an Account and a Contact. These test records are inserted into the database using the insert statement.
The testFunctionality() method is the actual test method where we perform actions that should be tested. In this example, we query the created test records and assert the expected results using the System.assertEquals() method.
The @isTest annotation is used to declare a class or method as a test class or test method, respectively. It allows the Apex runtime to identify and execute these code blocks as part of the testing process.
The example shown here is a simple illustration of a test class. In a real-world scenario, you would usually perform more complex operations and assertions as per your requirements.