Sub topic 12
Testing SOSL code
This chapter assumes you can write Apex test classes with @IsTest, Test.startTest(), and System.assertEquals. It also assumes you have read the earlier chapters on running SOSL in Apex, bind variables, and dynamic SOSL with Search.query.
Why SOSL tests need special handling
SOSL does not read your tables directly. It searches a text index that Salesforce updates asynchronously after records are saved. A test inserts records inside a transaction that is rolled back at the end, and the search index never sees them.
If you insert an Account in a test and then run a SOSL query for it, you get an empty result. The record exists and a SOQL query would find it. The index does not contain it. A test written this way either fails or, worse, passes because it only asserts that no exception was thrown.
Apex provides Test.setFixedSearchResults, which replaces the search step with a list of record IDs that you choose.
How Test.setFixedSearchResults works
You pass a List<Id>. Every SOSL query that runs afterwards in the same test, static or dynamic, uses that list instead of the real index. The behavior has these parts:
- No call, no results. Without
setFixedSearchResults, a SOSL query in a test returns empty lists. - The search term is ignored. The fixed IDs are returned whatever the
FINDtext says. A test cannot prove that'Acme*'matchesAcme Corp. - RETURNING still shapes the output. An ID is returned only if its object appears in the
RETURNINGclause. Each ID lands in the result list for its object, and only the fields you listed are populated. - Later calls replace earlier ones. Call it again with a different list to change the results mid-test.
- Records must exist. The IDs should belong to records you inserted in the test, so the query can load their fields.
flowchart TDDo not use the block above. The real diagram follows.
A basic test
This is the production class from the dynamic SOSL chapter, followed by its test.
public with sharing class AccountSearch {
public static List<Account> findAccounts(String userInput) {
String safe = String.escapeSingleQuotes(userInput);
String query = 'FIND \'' + safe + '\' IN NAME FIELDS RETURNING Account(Id, Name LIMIT 20)';
List<List<SObject>> results = Search.query(query);
return (List<Account>) results[0];
}
}@IsTest
private class AccountSearchTest {
@IsTest
static void findsFixedResult() {
Account acc = new Account(Name = 'Acme Test');
insert acc;
Test.setFixedSearchResults(new List<Id>{ acc.Id });
Test.startTest();
List<Account> found = AccountSearch.findAccounts('Acme');
Test.stopTest();
System.assertEquals(1, found.size());
System.assertEquals('Acme Test', found[0].Name);
}
}Call setFixedSearchResults before the code under test runs. Putting it before Test.startTest() is the usual convention, but it works inside the start/stop block as well, as long as it runs before the query.
Testing the empty case
A search that finds nothing is a real path in your code. Test it by not setting fixed results, or by setting an empty list.
@IsTest
private class AccountSearchEmptyTest {
@IsTest
static void returnsNothingWhenIndexHasNoMatch() {
insert new Account(Name = 'Acme Test');
// No setFixedSearchResults call: the query returns empty lists.
List<Account> found = AccountSearch.findAccounts('Acme');
System.assertEquals(0, found.size());
}
}This test leans on documented behavior, so it will keep passing. Its purpose is to confirm that your code handles an empty list without errors such as reading results[0][0].
Testing multi-object results
When RETURNING lists several objects, put IDs of each type in the fixed list. The result lists keep the order of the RETURNING clause, whatever order the IDs have in your list.
public with sharing class PeopleSearch {
public static List<List<SObject>> search(String term) {
return [
FIND :term IN NAME FIELDS
RETURNING Account(Id, Name), Contact(Id, FirstName, LastName)
];
}
}@IsTest
private class PeopleSearchTest {
@IsTest
static void groupsResultsByObject() {
Account acc = new Account(Name = 'Acme Corp');
insert acc;
Contact con = new Contact(LastName = 'Tester', AccountId = acc.Id);
insert con;
// The Contact ID comes first on purpose.
Test.setFixedSearchResults(new List<Id>{ con.Id, acc.Id });
Test.startTest();
List<List<SObject>> results = PeopleSearch.search('Acme');
Test.stopTest();
List<Account> accounts = (List<Account>) results[0];
List<Contact> contacts = (List<Contact>) results[1];
System.assertEquals(1, accounts.size());
System.assertEquals(1, contacts.size());
System.assertEquals(acc.Id, accounts[0].Id);
System.assertEquals(con.Id, contacts[0].Id);
}
}You can also check that an ID for an object missing from RETURNING is dropped. If you fix results with an Opportunity ID and the query returns only Account and Contact, both lists come back empty.
Making dynamic SOSL testable
Fixed results cannot check the text of a query, and a dynamic query is where bugs hide, such as missing escaping or a wrong field group. Move the string building into its own method that you can call directly.
public with sharing class AccountSearch {
@TestVisible
private static String buildQuery(String userInput) {
String safe = String.escapeSingleQuotes(userInput);
return 'FIND \'' + safe + '\' IN NAME FIELDS RETURNING Account(Id, Name LIMIT 20)';
}
public static List<Account> findAccounts(String userInput) {
List<List<SObject>> results = Search.query(buildQuery(userInput));
return (List<Account>) results[0];
}
}@IsTest
private class AccountSearchQueryTest {
@IsTest
static void escapesSingleQuotes() {
String query = AccountSearch.buildQuery('O\'Brien');
System.assert(query.contains('O\\\'Brien'), 'Quote should be escaped: ' + query);
}
@IsTest
static void usesNameFieldsGroup() {
String query = AccountSearch.buildQuery('Acme');
System.assert(query.contains('IN NAME FIELDS'));
}
}These tests check the query text, and they need no records and no fixed results. They fail if someone removes the call to escapeSingleQuotes.
Testing sharing and field access
with sharing still applies to SOSL, and fixed results do not bypass it. A user who cannot see a record does not get it back, even if its ID is in your list. To test that, run the query as a restricted user.
@IsTest
private class AccountSearchSharingTest {
@IsTest
static void restrictedUserDoesNotSeePrivateAccount() {
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;
Account acc = new Account(Name = 'Acme Private');
insert acc; // owned by the running (admin) user
Test.setFixedSearchResults(new List<Id>{ acc.Id });
List<Account> found;
System.runAs(u) {
found = AccountSearch.findAccounts('Acme');
}
// The result depends on your org's default sharing for Account.
System.debug('Visible to restricted user: ' + found.size());
}
}This example logs the count and does not assert it. The expected value depends on the Account sharing model in the org, which is Private in some orgs and Public Read Only in others. In your project, pick the sharing setup you rely on and assert the matching number. The same approach works for field-level security: run as a user whose profile hides a field, then check that the field is not populated, or that your WITH SECURITY_ENFORCED or WITH USER_MODE clause throws.
Limits inside tests
SOSL counts against governor limits in tests just as it does in production.
| Limit | Value |
|---|---|
| SOSL queries per synchronous transaction | 20 |
| Rows returned by one SOSL query | 2,000 |
Test.startTest() gives the code under test a fresh set of limits. Setup work before it, such as inserting data, does not use up the limits of the code you measure. If a method runs SOSL inside a loop, a test with more than 20 iterations will hit the limit, which is the failure you want to catch early.
Common mistakes
- Expecting results with no fixed list. The query returns empty lists, and the test fails or tests nothing.
- Asserting on the search term. Changing the term in the test never changes the result.
- Fixing IDs of the wrong object. An ID whose object is not in
RETURNINGis silently dropped. - Indexing results by assumption. Use the position of the object in
RETURNING, not the order of your ID list. - Forgetting
Test.startTest()andTest.stopTest(). Without them, setup work and the code under test share one set of limits. - Testing only the happy path. Cover the empty result, a single object, several objects, and a user without access.
Exercise
A developer inserts an Account named 'Globex Inc' in a test, then calls a method that runs FIND 'Globex*' IN NAME FIELDS RETURNING Account(Id, Name) and asserts that one Account is returned. The assertion fails with 0 results. What is the cause, and how do they fix the test?
Show answer
The search index never contains records inserted during a test, so the SOSL query returns empty lists. The fix is to call Test.setFixedSearchResults(new List<Id>{ acc.Id }) with the inserted Account's ID before the method runs. The query then returns that Account.
Exercise
A test calls Test.setFixedSearchResults with the IDs of one Contact and one Opportunity. The method under test runs SOSL with RETURNING Account(Id, Name), Contact(Id, LastName). What do results[0] and results[1] contain?
Show answer
results[0] is the Account list and is empty, because no Account ID was fixed. results[1] is the Contact list and holds the one Contact. The Opportunity ID is dropped because Opportunity is not in the RETURNING clause.
Exercise
Why should you move the construction of a dynamic SOSL string into its own @TestVisible method, and what can you assert on it that setFixedSearchResults cannot check?
Show answer
Fixed results ignore the search text, so they cannot show whether the query string is correct. A separate method returns the string, and a test can assert that it contains the escaped user input and the expected clauses, such as IN NAME FIELDS. This catches a removed escapeSingleQuotes call without needing records or an index.