Sub topic 15
Testing code that runs queries
This chapter assumes you can write inline SOQL, use bind variables, and know the basic governor limits. It also assumes you have written a simple Apex test class before.
Tests start with an empty database
Apex tests do not see the records in your org by default. Each test method starts with no Accounts, Contacts, or other business data. Data you insert in a test is rolled back when the test ends.
This isolation is useful. A test that depends on existing org data passes in one org and fails in another. Avoid @isTest(SeeAllData=true) unless you are testing something that truly needs org data, which is rare.
A reliable query test follows four steps:
- Arrange: insert the records the query should find, and any it should ignore.
- Act: run the code under test between
Test.startTest()andTest.stopTest(). - Assert: check the size and contents of the result.
- Repeat for the edge cases: no rows, many rows, and the wrong rows.
A basic query test
Insert one matching record and one non-matching record. This shows that the WHERE clause filters, not only that the query returns something.
@isTest
private class AccountQueryTest {
@isTest
static void findsOnlyTechnologyAccounts() {
insert new List<Account>{
new Account(Name = 'Test Tech', Industry = 'Technology'),
new Account(Name = 'Test Energy', Industry = 'Energy')
};
Test.startTest();
List<Account> result = [
SELECT Id, Name FROM Account WHERE Industry = 'Technology'
];
Test.stopTest();
Assert.areEqual(1, result.size());
Assert.areEqual('Test Tech', result[0].Name);
}
@isTest
static void returnsEmptyListWhenNothingMatches() {
List<Account> result = [
SELECT Id FROM Account WHERE Industry = 'Technology'
];
Assert.isTrue(result.isEmpty(), 'Expected no accounts in a clean test context');
}
}Test.startTest() and Test.stopTest() give the code between them a fresh set of governor limits. Setup work such as inserts does not use up the limits of the code you are testing.
Testing that queries stay bulk-safe
A query inside a loop works with one record and fails with 200. Test with a full trigger-sized batch, then check how many queries ran with Limits.getQueries().
public with sharing class ContactAccountNames {
public static Map<Id, String> namesByContact(List<Contact> contacts) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : contacts) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :accountIds]
);
Map<Id, String> result = new Map<Id, String>();
for (Contact c : contacts) {
Account a = accountsById.get(c.AccountId);
if (a != null) {
result.put(c.Id, a.Name);
}
}
return result;
}
}@isTest
private class ContactAccountNamesTest {
@isTest
static void usesOneQueryFor200Contacts() {
Account acct = new Account(Name = 'Bulk Parent');
insert acct;
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 200; i++) {
contacts.add(new Contact(LastName = 'Bulk' + i, AccountId = acct.Id));
}
insert contacts;
Test.startTest();
Map<Id, String> names = ContactAccountNames.namesByContact(contacts);
Integer queriesUsed = Limits.getQueries();
Test.stopTest();
Assert.areEqual(200, names.size());
Assert.areEqual(1, queriesUsed, 'Expected a single SOQL query');
}
}If someone later moves the query into the loop, this test fails with a limit exception or a wrong query count.
Testing permissions
A query with WITH USER_MODE depends on who runs it. Wrap the call in System.runAs() with a user whose profile lacks access, then assert that the expected exception occurs. Creating that user needs a profile lookup, which varies by org, so keep that setup in a shared helper method.
Common mistakes
- Querying for records the test never inserted, then asserting on an empty list by accident.
- Asserting only that a list is not empty, which hides wrong filters.
- Testing with one record, so loop-based queries go unnoticed.
- Forgetting that
Test.stopTest()is needed to finish asynchronous work before you query its results.
Exercise
Why should the test for a WHERE clause insert both a matching and a non-matching record?
Show answer
Inserting both shows that the filter excludes the wrong record. With only a matching record, the test would also pass if the query had no filter at all.
Exercise
How can a test confirm that code uses one query no matter how many records it processes?
Show answer
Insert about 200 records, call the code between Test.startTest() and Test.stopTest(), then assert that Limits.getQueries() equals 1.