Sub topic 15
Testing Code That Runs Queries
This chapter assumes you can write inline SOQL, use bind variables, and follow the bulk-safe pattern of collecting Ids and querying once. It also assumes you have written a basic Apex test class. Here you will learn how to test query code so the tests are reliable and catch real bugs.
Why tests must create their own data
Apex tests run in an isolated context. By default, a test cannot see the records that already exist in the org. It can see setup objects such as User and Profile. This is the behavior of @isTest(SeeAllData=false), which is the default.
This isolation has two consequences for query tests:
- A query in a test returns only records that the test, or a
@TestSetupmethod, created. - Any DML the test performs is rolled back when the test finishes, so tests do not leave data behind.
Do not use @isTest(SeeAllData=true) to get around this. A test that depends on org data passes in one sandbox and fails in another. It can also fail in production, where deployments run tests. A test that builds its own data behaves the same everywhere.
A first query test
Suppose this class is the code under test:
public with sharing class AccountService {
public static List<Account> findByIndustry(String industry) {
return [
SELECT Id, Name, Industry
FROM Account
WHERE Industry = :industry
ORDER BY Name
];
}
}A good test inserts matching and non-matching records. It checks that the filter includes the first group and excludes the second.
@isTest
private class AccountServiceTest {
@isTest
static void findByIndustryReturnsOnlyMatches() {
insert new List<Account>{
new Account(Name = 'Beta Tech', Industry = 'Technology'),
new Account(Name = 'Alpha Tech', Industry = 'Technology'),
new Account(Name = 'Gamma Energy', Industry = 'Energy')
};
Test.startTest();
List<Account> result = AccountService.findByIndustry('Technology');
Test.stopTest();
Assert.areEqual(2, result.size(), 'Only Technology accounts expected');
Assert.areEqual('Alpha Tech', result[0].Name, 'ORDER BY Name should sort ascending');
Assert.areEqual('Beta Tech', result[1].Name);
}
}The test includes a record that should not match. If it inserted only Technology accounts, a query with no WHERE clause would also pass.
Use the Assert class (Assert.areEqual, Assert.isTrue, Assert.isFalse, Assert.isNotNull, Assert.fail). The older System.assertEquals still works, but Assert reads more clearly. Always pass a message as the last argument, because it appears in the failure output.
Sharing setup data with @TestSetup
When several test methods need the same records, create them once in a @TestSetup method. Apex runs it once for the class. Each test method then starts with a fresh copy of that data, and changes one method makes are rolled back before the next method runs.
@isTest
private class AccountServiceSetupTest {
@TestSetup
static void makeData() {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 5; i++) {
accts.add(new Account(Name = 'Tech ' + i, Industry = 'Technology'));
}
insert accts;
}
@isTest
static void findsSetupRecords() {
List<Account> result = AccountService.findByIndustry('Technology');
Assert.areEqual(5, result.size());
}
@isTest
static void deletesDoNotLeakBetweenMethods() {
delete [SELECT Id FROM Account];
Assert.areEqual(0, AccountService.findByIndustry('Technology').size());
}
}The second method deletes every account. The first method is unaffected, whichever runs first.
Test the empty result
Many query bugs show up only when no rows match. If the code assigns a query to a single sObject, a missing row throws a QueryException. Write a test for the no-match case for every query method.
@isTest
private class EmptyResultTest {
@isTest
static void noMatchReturnsEmptyList() {
List<Account> result = AccountService.findByIndustry('Technology');
Assert.isTrue(result.isEmpty(), 'No records exist, so the list must be empty');
}
@isTest
static void singleRecordQueryThrowsWhenNothingMatches() {
try {
Account a = [SELECT Id FROM Account WHERE Name = 'No Such Account' LIMIT 1];
Assert.fail('Expected a QueryException');
} catch (QueryException e) {
Assert.isTrue(e.getMessage().contains('no rows'), e.getMessage());
}
}
}The second test documents the failure mode. In your own code, you would test that your class handles the empty list. Do not catch the QueryException that the query throws.
Test that queries are bulk-safe
A query inside a loop works with one record and fails with 200. Triggers deliver records in batches of up to 200, so test with at least that many.
You can also measure the query count directly. Limits.getQueries() returns the number of SOQL queries run so far in the current transaction.
public with sharing class ContactAccountService {
public static Map<Id, Account> accountsFor(List<Contact> contacts) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : contacts) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
return new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :accountIds]
);
}
}@isTest
private class ContactAccountServiceTest {
@isTest
static void usesOneQueryFor200Contacts() {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accts.add(new Account(Name = 'Bulk ' + i));
}
insert accts;
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 200; i++) {
contacts.add(new Contact(LastName = 'C' + i, AccountId = accts[i].Id));
}
Test.startTest();
Integer before = Limits.getQueries();
Map<Id, Account> result = ContactAccountService.accountsFor(contacts);
Integer used = Limits.getQueries() - before;
Test.stopTest();
Assert.areEqual(200, result.size());
Assert.areEqual(1, used, 'Query count must not grow with the number of records');
}
}The contacts are never inserted. The method under test only reads AccountId, so in-memory records are enough. Skipping needless DML keeps the test fast.
The query-count assertion catches a regression where someone later moves the query into a loop. At 200 records that mistake would hit the limit of 100 synchronous queries.
What Test.startTest and Test.stopTest do
Everything between Test.startTest() and Test.stopTest() gets a fresh set of governor limits. Setup code before startTest does not count against the limits for the code under test. This matters because your setup DML would otherwise use up part of the budget you are trying to measure.
Test.stopTest() also runs any asynchronous work (such as @future methods and Queueable jobs) that the code started, and waits for it to finish. Assert after stopTest() when you test async code that queries.
Call each of them at most once per test method.
Test permissions with System.runAs
Tests run in system mode by default, which ignores the running user's sharing and field-level security. If your query uses WITH USER_MODE, or the class declares with sharing, run the test as a user whose access you control.
@isTest
private class UserModeQueryTest {
@isTest
static void standardUserSeesOwnAccount() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User u = new User(
Alias = 'tuser',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Tester',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
Username = 'tuser' + System.currentTimeMillis() + '@example.com'
);
insert u;
System.runAs(u) {
insert new Account(Name = 'Owned by tester', Industry = 'Technology');
List<Account> result = [
SELECT Id, Name FROM Account WHERE Industry = 'Technology' WITH USER_MODE
];
Assert.areEqual(1, result.size());
}
}
}The account is created inside the runAs block, so the test user owns it and can see it under any sharing model. If the test created the account outside the block, the result would depend on the org's sharing settings.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Using `SeeAllData=true` | Test depends on org data and breaks in other orgs | Create data in the test or in `@TestSetup` |
| Inserting only matching records | A missing `WHERE` clause goes unnoticed | Add a record that must not match |
| Testing one record only | Query-in-loop bugs pass | Test with 200 records and check `Limits.getQueries()` |
| No assertions | The test gives coverage but proves nothing | Assert on size, field values, and order |
| Skipping the empty case | `QueryException` appears in production | Test with no matching rows |
| Hardcoded Ids or usernames | Tests fail in other orgs or on rerun | Query for Ids or generate unique values |
Exercise
A trigger handler runs SELECT Id, Name FROM Account WHERE Id IN :accountIds once per call. Describe a test that proves the handler stays within the SOQL limit when 200 contacts are inserted at once. Name the two Apex features you would use.
Show answer
Insert 200 accounts and build 200 contacts that reference them. Record Limits.getQueries() before calling the handler, then call it between Test.startTest() and Test.stopTest(). Subtract the earlier count from Limits.getQueries() afterward and assert the difference is 1, and assert the result map holds 200 accounts. The two features are Limits.getQueries() and Test.startTest()/Test.stopTest().
Exercise
Why does a test for AccountService.findByIndustry('Technology') insert an account whose industry is 'Energy'?
Show answer
The extra record must not appear in the result. If the query lost its WHERE clause, the Energy account would be returned and the size assertion would fail. Without that record, the test would pass even with a broken filter.
Exercise
A test passes on your sandbox but fails when deployed to production. It contains @isTest(SeeAllData=true) and queries [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 1]. What is the likely cause, and how do you fix it?
Show answer
The test relies on an 'Acme' account that exists in the sandbox but not in production, so the query returns no rows and throws a QueryException. Remove SeeAllData=true, insert an 'Acme' account in the test (or in @TestSetup), and query for that record.