Apex Testing (Test Classes & Methods)

Apex Testing

What is Apex Testing?

Apex testing is the process of writing unit tests in the Salesforce Apex language to verify that your code works as intended. It involves creating test classes and methods to simulate real user actions and to validate the output of your logic.

|Salesforce requires at least 75% code coverage for Apex classes and triggers to be deployed to a production environment.

Why is Apex Testing Important?

• Ensures your code works correctly.

• Helps prevent bugs and logic errors.

• Required for deployment to production.

• Allows performance and behavior testing.

Test Class

A test class is an Apex class that contains test methods—special methods that test your logic using the @isTest annotation.

Basic Structure

@isTest

private class SampleTestClass {

@isTest

static void sampleTestMethod() {

// 1. Prepare test data

// 2. Call method to test

// 3. Assert the result

}

}

Syntax Components Explained

Part Syntax Explanation
Test Class @isTest private class @isTest tells Salesforce this is a test class.
Declaration ClassNameTest it’s not used in production logic
Test Method @isTest static void Marks a method as a test method. Must be static and return void.
Start/Stop/Test Test.startTest() Test.stopTest() Optional, but useful to separate setup from logic under test, and test governor limits.
Assertions System.assert() System.assertEquals() Used to compare expected vs actual results. Validates your logic.

Example 1. Create an Account Record

Business Logic:

public class AccountService {

public static void createAccount(String accName) {

Account acc = new Account(Name = accName);

insert acc;

}

}

Explanation :

• A method createAccount takes a name and creates a new Account record in Salesforce.

• It sets the name of the account and inserts it into the database.

Test Class :

@isTest

private class AccountServiceTest {

@isTest

static void testCreateAccount() {

Test.startTest();

AccountService.createAccount(‘Acme Corp’);

Test.stopTest();

Account acc = [SELECT Name FROM Account WHERE Name = ‘Acme Corp’ LIMIT 1];

System.assertEquals(‘Acme Corp’, acc.Name);

}

}

Explanation :

• It checks if the createAccount method actually creates an account with the correct name.

• It uses System.assertEquals to validate that the inserted account has the correct name.

Run the Test Class:

1. Open Developer Console.

2. Click Test > New Run.

3. Select your test class (e.g., AccountServiceTest).

4. Click Run.

Check Results and Code Coverage,

After the test runs:

• You’ll see a Success or Failure status.

• You can open logs to debug failures.

• Check code coverage in the Developer Console:

• Click Test > Code Coverage > Show Code Coverage.

• It highlights covered lines in blue, uncovered in red.

Expected Output :

• Test will pass if the account is created with the name “Acme Corp”.

• System.assertEquals(‘Acme Corp’, acc.Name) will be true.

Test Result :

testCreateAccount — PASS

Example 2. Handling Missing Required Fields (Negative Test)

Business Logic :

public class ContactHandler {

public static void createContact(String lastName) {

if (String.isEmpty(lastName)) {

throw new IllegalArgumentException(‘Last Name is required’);

}

Contact c = new Contact(LastName = lastName);

insert c;

}

}

Explanation :

• It creates a contact only if the last name is provided.

• If the last name is empty, it throws an error.

Test Class:

@isTest

private class ContactHandlerTest {

@isTest

static void testCreateContact_MissingLastName() {

try {

ContactHandler.createContact(”);

System.assert(false, ‘Expected exception was not thrown’);

} catch (Exception e) {

System.assert(e.getMessage().contains(‘Last Name is required’));

}

}

}

Explanation :

• It tries to create a contact without a last name to see if the system throws an error.

• It checks that the correct error message is returned.

Expected Output :

• Test will pass if an exception is thrown with message “Last Name is required”.

• System.assert inside catch block will be true.

Test Class:

testCreateContact_MissingLastName — PASS

Example 3. Updating a Record

Business Logic :

public class AccountUpdater {

public static void updateIndustry(Id accountId, String newIndustry) {

Account acc = [SELECT Id, Industry FROM Account WHERE Id = :accountId];

acc.Industry = newIndustry;

update acc;

}

}

Explanation :

• It finds an account by ID and updates its Industry field.

Expected Output :

• Test will pass if the Industry field of the account is updated to “Technology”.

Test Result :

testUpdateIndustry — PASS

Example 4. Testing a Trigger

Trigger:

trigger AccountTrigger on Account (before insert) {

for (Account acc : Trigger.new) {

if (acc.Industry == null) {

acc.Industry = ‘Default’;

}

}

}

Explanation :

• Before an account is inserted, it checks if the Industry is missing.

• If it’s missing, it automatically sets it to “Default”.

Test Class:

for (Opportunity opp : oppList) {
Account acc = [SELECT Name FROM Account WHERE Id = :opp.AccountId]; // SOQL inside loop
}

Explanation :

• It creates an account without specifying Industry.

• It then checks whether the trigger automatically set Industry to “Default”.

Expected Output :

• Test will pass if an account is created with no industry and the trigger assigns “Default”.

Best Practices for Apex Testing

• Use meaningful test method names

• Cover positive, negative, and edge cases

• Use System.assert to validate behavior

• Avoid using real org data – always create test data

• Keep tests fast and isolated

Tasks For Practice

1. Create a class AccountManager with a method createAccount that takes an account name and creates an Account record.
Write a test class that verifies the account is created with the correct name.

2. Write a before-insert trigger on Contact that assigns “No Email” to the Email field if it is blank.
Write a test class that verifies the trigger assigns this default.

3. Write a method in LeadService that inserts a Lead but throws an exception if the Company field is blank.
Write a test to check that the exception is thrown when Company is blank.

4. Create a class ContactUpdater with a method that updates a Contact’s Phone number by Id.
Write a test to verify the phone number is updated correctly.