Sub topic 11
Writing Tests for Controller Methods
This chapter assumes you can write basic Apex classes, SOQL and DML. It also assumes you know how @AuraEnabled methods are called from components, and how AuraHandledException and with sharing work. Here you will test a controller's happy path, its error path, and its security behavior.
Why test controllers like any other Apex
An @AuraEnabled method is an ordinary static method. A test does not need a component, a browser or the wire service. It creates its own data, calls the method directly and asserts on the result.
Salesforce requires 75% code coverage to deploy to production. Coverage only shows which lines ran. Assertions show whether the method behaved correctly, so write both.
Testing the read path
This test covers the getContacts method from earlier in the tutorial.
@IsTest
private class ContactControllerTest {
@IsTest
static void returnsContactsForAccount() {
Account a = new Account(Name = 'Test Account');
insert a;
insert new Contact(LastName = 'Smith', AccountId = a.Id);
Test.startTest();
List<Contact> result = ContactController.getContacts(a.Id);
Test.stopTest();
Assert.areEqual(1, result.size(), 'Expected one contact for the account');
}
}Three points about this test:
- It creates its own records. Tests do not see existing org data by default, and relying on it makes tests fragile.
Test.startTest()andTest.stopTest()give the code under test a fresh set of governor limits. Your setup DML does not count against them.Assert.areEqual(expected, actual, message)is the current assertion API. The message appears in the failure output.
Testing the error path
The createContact method catches a DmlException and rethrows it as an AuraHandledException. A test must trigger the failure and check the thrown exception. LastName is required on Contact, so passing a blank value forces the failure.
@IsTest
private class ContactControllerErrorTest {
@IsTest
static void wrapsDmlFailureInAuraHandledException() {
Account a = new Account(Name = 'Test Account');
insert a;
Boolean caught = false;
Test.startTest();
try {
ContactController.createContact('', a.Id);
} catch (AuraHandledException e) {
caught = true;
Assert.isTrue(
e.getMessage().contains('Could not create the contact'),
'Unexpected message: ' + e.getMessage()
);
}
Test.stopTest();
Assert.isTrue(caught, 'Expected an AuraHandledException');
}
}The caught flag matters. Without it, the test passes silently if no exception is thrown, because the catch block never runs.
A known quirk with exception messages
In a test, getMessage() on an AuraHandledException can return a generic "Script-thrown exception" instead of your text. This happens when the exception was built with only a message argument. To make the message readable, call setMessage() on the exception before you throw it.
AuraHandledException ex = new AuraHandledException('Could not create the contact');
ex.setMessage('Could not create the contact');
throw ex;Testing as a restricted user
Methods that use WITH USER_MODE or insert as user enforce the running user's permissions. Test classes run in system mode by default, so a plain test never exercises that enforcement. Use System.runAs with a user who lacks access.
@IsTest
private class ContactControllerSecurityTest {
@IsTest
static void blocksUserWithoutContactAccess() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Minimum Access - Salesforce' LIMIT 1];
User u = new User(
Alias = 'noaccess',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'NoAccess',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
TimeZoneSidKey = 'America/Los_Angeles',
ProfileId = p.Id,
UserName = 'noaccess' + System.currentTimeMillis() + '@example.com'
);
insert u;
Account a = new Account(Name = 'Test Account');
insert a;
Boolean blocked = false;
System.runAs(u) {
try {
ContactController.getContacts(a.Id);
} catch (System.QueryException e) {
blocked = true;
}
}
Assert.isTrue(blocked, 'Expected a QueryException for a user without access');
}
}The "Minimum Access - Salesforce" profile grants no object access beyond the basics. This is why the query fails. If your org has renamed or removed that profile, pick another low-access profile.
What to cover
The diagram shows the paths a controller test suite should reach.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| No assertion in the test | Coverage passes but bugs go unseen | Assert on return values and state |
| `catch` without a flag | Test passes when no exception is thrown | Track that the catch ran |
| Relying on org data | Test fails in other orgs or sandboxes | Create records in the test |
| Never using `System.runAs` | Security enforcement is untested | Test with a restricted user |
Exercise
A test calls a method that is supposed to throw an AuraHandledException. The method has a bug and throws nothing. The test wraps the call in try/catch and asserts inside the catch block only. Does the test fail? How do you fix it?
Show answer
It does not fail. No exception is thrown, so the catch block and its assertion never run. Set a Boolean flag to true inside the catch block, then assert after the try/catch that the flag is true. Alternatively, call Assert.fail('Expected an exception') on the line after the method call inside the try block.
Exercise
Why does a test for a method using WITH USER_MODE need System.runAs?
Show answer
Test methods run in system mode by default, so the running user (the test runner) has full access and the permission checks never fail. System.runAs executes the code as a user with limited permissions, which lets the test confirm that access is blocked.