Clarification on Unit Testing a method that runs a SOSL query

I have a controller method that uses a SOSL query to generate a list of options. It works when used in the VF page, but the unit test is failing; logging shows the SOSL query is returning no results.

I found this answer to a similar question which states that testing SOSL “is somewhat messy because of indexing delay”. It suggests the use of Test.setFixedSearchResults(), and links to this documentation on testing and SOSL queries.

The documentation states that any SOSL query “that is added to an Apex test method returns an empty set of search results when the test method executes”. The explanation and the sample code only addresses SOSL queries that are actually in a test method, but doesn’t address SOSL queries that are contained in methods called by a test method. There is a distinction.

SO my question: Are all SOSL queries contained in non-test methods guaranteed to return no results when invoked by a test method? If yes, is this explicitly documented anywhere? The documentation link above is not clear to me (and I’ve submitted feedback to that effect).


I haven’t seen documentation other than what you linked to and the documentation of Test.setFixedSearchResults().

I understand the distinction you are making. I have written tests on classes that contain methods that use SOSL. As part of pre test set up, in the test method, I have used the fixedSearchResults. I have never had any issues. Something like the following definitely works. If you remove the Test.setFixedSearchResults it definitely doesn’t work.

Unit Test Class

private class SoslTest {

    static void testSearch() {
        Account acct = new Account(Name = 'Acme');
        insert acct;

        Id [] fixedSearchResults = new Id[]{acct.Id};

        List<List<sObject>> results =;
        System.assertEquals(acct.Id, results[0][0].Id, 'Account Ids should match'); 

Class Under Test

public class SoslService{

    public static List<List<sObject>> search(String term) {
        return [FIND 'test' 
                IN ALL FIELDS RETURNING 
                Account(id, name WHERE name = :term)];   

Note that the FIND portion is irrelevant. It is just the WHERE clause that needs to match.

Source : Link , Question Author : Jason Clark , Answer Author : Bahman.A

Leave a Comment