How to Effectively Write Apex Unit Tests?

Question:
I am new to writing Apex unit tests in Salesforce and want to understand how to create effective tests. Could you explain the process of writing an Apex unit test, including how to create test data, execute the code to be tested, and validate the results? Additionally, I would like to know how to ensure my tests are isolated from organization data and best practices for adding meaningful assertions. Can you provide examples to illustrate these concepts?
Answer:
Writing an Apex unit test involves understanding and applying key principles of testing within the Salesforce platform. Unit tests ensure that your code behaves as expected under various conditions and adhere to Salesforce’s requirement of 75% code coverage for deployment. Here’s a detailed explanation to guide you.
To begin, unit testing typically follows three steps: creating test data, executing the code, and asserting results.
CRS Info Solutions provides top-notch Salesforce online training with real-time projects, certification guidance, interview coaching, and a practical, job-ready approach.
1. Creating Test Data:
- In Salesforce, unit tests operate in an isolated context, meaning they cannot access organization data except for metadata records. You need to create sample records within your test class. This ensures your tests are self-contained and consistent.
- For example, to test code that works with
Accountrecords, you can create test data like this:
@isTest
public class AccountTest {
@isTest
static void testAccountCreation() {
Account acc = new Account(Name = 'Test Account');
insert acc;
}
}Here’s what happens step-by-step:
@isTestAnnotation: This marks theAccountTestclass andtestAccountCreationmethod as a test class and test method. Salesforce executes only methods with this annotation during test runs.- Creating Test Data: An
Accountobject is instantiated with theNamefield set to “Test Account.” - Inserting Test Data: The
insertDML operation saves this record into the test database. Since Salesforce isolates test data, this record won’t affect your actual org’s data.
This is a simple test, typically used to verify that a DML operation executes successfully.
If your test requires the same setup for multiple test methods, you can use the @testSetup annotation to centralize this logic.
@isTest
public class AccountTest {
@testSetup
static void setup() {
Account acc = new Account(Name = 'Test Account');
insert acc;
}
}@testSetupAnnotation: This designates thesetupmethod as a preparation method that runs before each test method in the class. The test data it creates is shared across all methods.- Centralized Test Data: By creating an account record in the
@testSetupmethod, we avoid duplicating setup logic in multiple test methods. - Isolation and Reusability: The data created here is isolated and can be reused for consistent test conditions.
This approach is beneficial when multiple test methods in the same class need similar data.
2.Executing the Code:
After setting up your test data, the next step is to execute the code you are testing. This is done by calling the method or functionality you want to validate.
For example:
public class AccountHandler {
public static void updateAccountIndustry(Id accountId, String industry) {
Account acc = [SELECT Id, Industry FROM Account WHERE Id = :accountId];
acc.Industry = industry;
update acc;
}
}
@isTest
public class AccountHandlerTest {
@isTest
static void testUpdateAccountIndustry() {- Purpose: This method updates the
Industryfield of an account record identified by itsId. - SOQL Query: It retrieves the account record using the
Idparameter. - Field Update and DML: The
Industryfield is set to the providedindustryvalue, and the updated record is saved with theupdatestatement.
The unit test for the method:
@isTest
public class AccountHandlerTest {
@isTest
static void testUpdateAccountIndustry() {
Account acc = new Account(Name = 'Test Account');
insert acc;
AccountHandler.updateAccountIndustry(acc.Id, 'Technology');
}
}- Creating Test Data: A new account record is created and inserted into the test database, mimicking real-world data.
- Executing the Code: The
updateAccountIndustrymethod is invoked with theIdof the test account and the desiredIndustryvalue (“Technology”). - Verification: While this test lacks explicit assertions, the primary purpose here is to ensure that the method executes without errors. Assertions should be added to verify the behavior.
Enhancing the Test with Assertions
To make the test more meaningful, we can add assertions to validate that the Industry field was correctly updated:
@isTest
public class AccountHandlerTest {
@isTest
static void testUpdateAccountIndustry() {
Account acc = new Account(Name = 'Test Account');
insert acc;
AccountHandler.updateAccountIndustry(acc.Id, 'Technology');
Account updatedAcc = [SELECT Industry FROM Account WHERE Id = :acc.Id];
System.assertEquals('Technology', updatedAcc.Industry, 'Industry field was not updated correctly.');
}
}Key Changes:
- After calling the
updateAccountIndustrymethod, a SOQL query retrieves the updated account. System.assertEqualsis used to check that theIndustryfield matches the expected value (“Technology”). This ensures the code works as intended.
Assertions are vital because they confirm that the results of the test match expectations, making the test robust and meaningful.
Summing Up:
Writing effective Apex unit tests is crucial for ensuring robust, maintainable, and deployable code in Salesforce. By creating isolated and repeatable test data, executing targeted code paths, and writing meaningful assertions, you can validate your logic under various scenarios. Adhering to best practices, such as avoiding seeAllData=true and using tools like @testSetup for test data organization, ensures your tests remain reliable and unaffected by org-level changes. Combining these principles with Salesforce’s powerful testing tools and frameworks enables developers to achieve high code quality, meet coverage requirements, and build confidence in their applications.
Kickstart Your Salesforce Career with Training in Hyderabad
Ready to boost your career with Salesforce? CRS Info Solutions offers top-tier Salesforce training in Hyderabad, designed to provide you with the skills needed to excel in the dynamic Salesforce ecosystem. Our expert-led courses cover critical modules like Salesforce Admin, Developer, and AI, with an emphasis on real-time project experience to ensure you gain hands-on expertise. Whether you’re a beginner or an experienced professional, our training prepares you for the challenges of the Salesforce world.
Our Salesforce training in Hyderabad focuses on practical, industry-relevant learning. With personalized guidance, comprehensive course materials, and expert support for certification and interview prep, we make sure you’re job-ready. Don’t wait—enroll today for a free demo session and take the first step towards a successful Salesforce career!

