Sub topic 11
Writing tests for controller methods
This chapter shows how to test the Apex controller methods that Lightning components call. It assumes you can write basic Apex test classes, and that you know the @AuraEnabled, cacheable=true, AuraHandledException and WITH USER_MODE material from earlier chapters. It reuses the ContactController and AccountSummaryController classes from those chapters.
What an AuraEnabled test is
An @AuraEnabled method is an ordinary static Apex method. The annotation only changes who is allowed to call it. A test class can call ContactController.getContacts(accountId) directly, with no component, no wire adapter and no browser.
This has two consequences:
- Apex tests cover the server half of the call. They cannot check that a
@wirereruns whenrecordIdchanges, or that the component showserror.body.message. Those belong in Jest tests for the component. - The annotation adds no special test behavior. The usual rules apply: create your own data, assert on results, and cover both success and failure paths.
Salesforce requires 75% Apex coverage to deploy to production. Coverage is a minimum. A test that calls a method without asserting anything gives you coverage and no protection.
The shape of a controller test
Most controller tests follow the same steps.
Build data in the test or in a @TestSetup method. Avoid @IsTest(SeeAllData=true). Existing org data makes tests fail in other orgs and hides assumptions about what the method returns.
Test.startTest() and Test.stopTest() give the code between them a fresh set of governor limits. They also force asynchronous work to finish. Put only the call under test between them.
Testing a read method
The first test in this tutorial checks the happy path. A second test covers an edge case in the same method, the LIMIT 50 clause. The @TestSetup method runs once and its data is available to every test method in the class.
@IsTest
private class ContactControllerTest {
@TestSetup
static void makeData() {
insert new Account(Name = 'Test Account');
}
@IsTest
static void returnsContactsForAccountInNameOrder() {
Account a = [SELECT Id FROM Account LIMIT 1];
insert new List<Contact>{
new Contact(LastName = 'Smith', AccountId = a.Id),
new Contact(LastName = 'Adams', AccountId = a.Id)
};
Test.startTest();
List<Contact> result = ContactController.getContacts(a.Id);
Test.stopTest();
Assert.areEqual(2, result.size(), 'Expected both contacts');
Assert.areEqual('Adams', result[0].LastName, 'Results should be ordered by name');
}
@IsTest
static void capsResultsAtFifty() {
Account a = [SELECT Id FROM Account LIMIT 1];
List<Contact> many = new List<Contact>();
for (Integer i = 0; i < 60; i++) {
many.add(new Contact(LastName = 'Person ' + i, AccountId = a.Id));
}
insert many;
Test.startTest();
List<Contact> result = ContactController.getContacts(a.Id);
Test.stopTest();
Assert.areEqual(50, result.size(), 'The query limit should cap the list');
}
@IsTest
static void returnsEmptyListForAccountWithoutContacts() {
Account a = [SELECT Id FROM Account LIMIT 1];
List<Contact> result = ContactController.getContacts(a.Id);
Assert.isTrue(result.isEmpty(), 'An account with no contacts should give an empty list');
}
}The empty case matters because a @wire property receives an empty array from this method. Your template then renders nothing. A method that returned null instead would make data behave differently in the component.
Testing a wrapper class result
A wrapper class is an inner class. Tests read its fields as normal Apex fields. The @AuraEnabled annotation on those fields matters only when the object is serialized for the component, so Apex cannot prove that an annotation is present. Test the values your component depends on.
@IsTest
private class AccountSummaryControllerTest {
@IsTest
static void summaryCountsContacts() {
Account a = new Account(Name = 'Summary Co');
insert a;
insert new List<Contact>{
new Contact(LastName = 'One', AccountId = a.Id),
new Contact(LastName = 'Two', AccountId = a.Id)
};
AccountSummaryController.Summary s = AccountSummaryController.getSummary(a.Id);
Assert.areEqual('Summary Co', s.name);
Assert.areEqual(2, s.contactCount);
}
}Because serialization is not visible to Apex, a missing @AuraEnabled on a wrapper member is easy to miss. The Apex test passes and the component sees undefined. Catch this in review, or in a Jest test that mocks the real response shape.
Testing a write method and its error path
A method that performs DML needs two tests: one for success and one for failure. Verify the success case by querying the database, not by trusting the returned object.
@IsTest
private class ContactControllerWriteTest {
@IsTest
static void createContactSavesRecord() {
Account a = new Account(Name = 'Write Test');
insert a;
Test.startTest();
Contact created = ContactController.createContact('Jones', a.Id);
Test.stopTest();
Contact saved = [SELECT LastName, AccountId FROM Contact WHERE Id = :created.Id];
Assert.areEqual('Jones', saved.LastName);
Assert.areEqual(a.Id, saved.AccountId);
}
@IsTest
static void createContactWithoutLastNameThrowsAuraHandledException() {
Account a = new Account(Name = 'Error Test');
insert a;
try {
ContactController.createContact('', a.Id);
Assert.fail('Expected an AuraHandledException');
} catch (AuraHandledException e) {
Assert.isTrue(
e.getMessage().startsWith('Could not create the contact'),
'Unexpected message: ' + e.getMessage()
);
}
}
}Assert.fail throws an AssertException. The catch block only handles AuraHandledException, so a method that fails to throw makes the test fail, as it should.
An empty last name violates the required field on Contact, so the insert raises a DmlException and the controller converts it. The failure is real and needs no mocking.
The AuraHandledException message gotcha
The error test above fails against the controller as written earlier. AuraHandledException has an unusual rule. If you construct it with a message, the client receives that message, but getMessage() in Apex returns Script-thrown exception. Calling setMessage fixes this. Set the message explicitly, which makes your own tests meaningful too.
public with sharing class ContactController {
@AuraEnabled
public static Contact createContact(String lastName, Id accountId) {
try {
Contact c = new Contact(LastName = lastName, AccountId = accountId);
insert as user c;
return c;
} catch (DmlException e) {
String message = 'Could not create the contact: ' + e.getMessage();
AuraHandledException ex = new AuraHandledException(message);
ex.setMessage(message);
throw ex;
}
}
}Testing sharing and permissions
Security behavior is part of the method's contract, so test it. Use System.runAs to run the call as a user with limited access. runAs applies record sharing for that user. Because the query uses WITH USER_MODE, object and field permissions are checked against the runAs user too.
Two details help here:
- Create the user in the test method, with the account in
@TestSetup. Inserting aUserand a record such as anAccountin the same transaction causes a mixed DML error. runAsdoes not check whether the user can access the Apex class itself. It only verifies data access inside the code.
@IsTest
private class ContactControllerSecurityTest {
@TestSetup
static void makeData() {
insert new Account(Name = 'Secure Account');
}
@IsTest
static void userWithoutContactAccessIsDenied() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Minimum Access - Salesforce' LIMIT 1];
User u = new User(
Alias = 'noacc',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'NoAccess',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'noaccess' + System.currentTimeMillis() + '@example.com'
);
insert u;
Account a = [SELECT Id FROM Account LIMIT 1];
System.runAs(u) {
try {
ContactController.getContacts(a.Id);
Assert.fail('Expected the query to be denied');
} catch (QueryException e) {
Assert.isNotNull(e.getMessage());
}
}
}
}The Minimum Access - Salesforce profile has no object permissions, which makes it a good user for denial tests. If your org lacks that profile, create a permission-limited one in your metadata. Test the opposite case too: a user with the right permissions should get data, so you know the denial test is failing for the right reason.
What to test and how
| Behavior | Where to test it | Technique |
|---|---|---|
| Query results, ordering, limits | Apex test | Insert data, call the method, assert on the list |
| Empty results | Apex test | Call with an account that has no children |
| DML success | Apex test | Call, then re-query the record |
| Error messages | Apex test | `try`/`catch` with `Assert.fail` |
| Sharing and field permissions | Apex test | `System.runAs` with a restricted user |
| Wire reruns, refresh, error display | Jest test | Mock the Apex import and the wire adapter |
Common mistakes
- Asserting nothing. A call with no
Assertstill counts toward coverage but proves nothing. - Using
SeeAllData=true. Tests then depend on the org's data and break in sandboxes and scratch orgs. - Testing only the happy path. The error branch is where untested code usually sits, and where users see failures.
- Testing as an admin only. An admin bypasses most permission problems, so a security bug is never exposed. Add at least one restricted-user test for each method that reads or writes data.
- Putting setup between
startTestandstopTest. This hides how many governor limits the real call consumes.
Exercise
A teammate writes a test for getContacts that runs as a System Administrator and passes. The method uses WITH USER_MODE. Which test would show that field-level security is enforced, and why must the test avoid creating the User and the Account in the same transaction?
Show answer
Add a test that creates a user with a restricted profile (for example Minimum Access - Salesforce, or a profile without read access to the Contact fields) and calls the method inside System.runAs(user). Assert that a QueryException is thrown, with Assert.fail after the call to catch the case where no exception occurs. An administrator has access to everything, so the original test cannot fail on a permission problem. The User is a setup object, and inserting it with a non-setup object such as Account in one transaction causes a mixed DML error. Put the account in @TestSetup, or insert the user inside a separate runAs block, so the two inserts run in different transactions.
Exercise
A test calls createContact with an empty last name and asserts that e.getMessage() starts with Could not create the contact. It fails with the message Script-thrown exception. What change fixes it?
Show answer
Call setMessage on the AuraHandledException before throwing it, using the same text passed to the constructor. Without setMessage, getMessage() in Apex returns Script-thrown exception, even though the client receives the constructor message.