Sub topic 12
Testing SOSL Code
This chapter assumes you can write SOSL in Apex, read the List<List<SObject>> result, and write basic Apex tests with @IsTest, Test.startTest(), and System.assertEquals.
Why SOSL tests need special handling
SOSL searches a text index, not the database tables. Salesforce updates that index asynchronously. A record you insert inside a test is usually not in the index yet when the next line runs. A SOSL query in a test therefore returns an empty list, even though the record exists.
Your test can't wait for the index. Salesforce gives you Test.setFixedSearchResults instead.
Using Test.setFixedSearchResults
Test.setFixedSearchResults(List<Id>) tells the platform which record IDs every SOSL query in the test should return. The query still runs, so these parts still apply:
- The
RETURNINGclause decides which objects and fields come back. - Per-object
WHERE,ORDER BY, andLIMITstill filter the fixed IDs. - Sharing and field access rules still apply.
The fixed IDs replace only the text-matching step. Your search terms are not checked. A query for 'Zebra' returns Acme Test if you listed its ID.
Call the method before the SOSL runs. Calling it before Test.startTest() keeps the setup separate from the code under 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());
}
}What to assert
Because the search terms are bypassed, a test like this checks your code around the search. Useful assertions include:
- The result list has the expected size.
- The returned record has the expected ID and field values.
- Your code reads the correct index from the result. In a query with two objects,
results[0]is the first object inRETURNINGandresults[1]is the second. - Your code handles an empty result without errors.
For the empty case, don't call setFixedSearchResults. Without it, the test search returns nothing, so you can confirm that your method returns an empty list.
@IsTest
static void returnsEmptyListWhenNothingMatches() {
Test.startTest();
List<Account> found = AccountSearch.findAccounts('NoSuchAccount');
Test.stopTest();
System.assertEquals(0, found.size());
}Add this method inside AccountSearchTest.
Testing a filter
Fixed results still pass through per-object filters. You can use this to test a WHERE clause. Insert two accounts, list both IDs, and run a query that filters on a field. Only the matching account should come back.
@IsTest
private class FilteredSearchTest {
@IsTest
static void whereClauseStillApplies() {
Account tech = new Account(Name = 'Acme Tech', Industry = 'Technology');
Account other = new Account(Name = 'Acme Farm', Industry = 'Agriculture');
insert new List<Account>{ tech, other };
Test.setFixedSearchResults(new List<Id>{ tech.Id, other.Id });
Test.startTest();
List<List<SObject>> results = [
FIND 'Acme' IN NAME FIELDS
RETURNING Account(Id, Name WHERE Industry = 'Technology')
];
Test.stopTest();
List<Account> accounts = (List<Account>) results[0];
System.assertEquals(1, accounts.size());
System.assertEquals(tech.Id, accounts[0].Id);
}
}Common errors
| Symptom | Likely cause |
|---|---|
| The search returns no records | `setFixedSearchResults` was not called, or it ran after the query |
| A record you did not expect is returned | Fixed results ignore the search terms, so any listed ID can match |
| Wrong object in the result | `results[n]` does not match the order in `RETURNING` |
| A listed record is missing | A `WHERE` clause or sharing rule excluded it |
Exercise
A test inserts an Account named 'Globex', then runs a SOSL query for 'Globex' without calling Test.setFixedSearchResults. The assertion expects one result but fails with zero. Why, and how do you fix it?
Show answer
New records are not reliably in the search index during a test, so the query finds nothing. Collect the inserted record's ID and call Test.setFixedSearchResults(new List<Id>{ acc.Id }) before the query runs, preferably before Test.startTest().
Exercise
You call Test.setFixedSearchResults with the IDs of three accounts. Your query has a per-object clause, Account(Id, Name WHERE Industry = 'Technology'), and only one account has that industry. How many accounts does the query return?
Show answer
One. The fixed IDs replace only the text matching, so the WHERE clause still filters the three accounts.