To ensure that test methods always behave in a predictable way, any Salesforce Object Search Language (SOSL) query that is added to an Apex test method returns an empty set of search results when the test method executes. If you do not want the query to return an empty list of results, you can use the Test.setFixedSearchResults system method to define a list of record IDs that are returned by the search. All SOSL queries that take place later in the test method return the list of record IDs that were specified by the Test.setFixedSearchResults method. Additionally, the test method can call Test.setFixedSearchResults multiple times to define different result sets for different SOSL queries. If you do not call the Test.setFixedSearchResults method in a test method, or if you call this method without specifying a list of record IDs, any SOSL queries that take place later in the test method return an empty list of results.
The list of record IDs specified by the Test.setFixedSearchResults method replaces the results that would normally be returned by the SOSL query if it were not subject to any WHERE or LIMIT clauses. If these clauses exist in the SOSL query, they are applied to the list of fixed search results.
Note:
1. Although the record may not match the query string in the FIND clause, the record is passed into the RETURNING clause of the SOSL statement.
2. If the record matches the WHERE clause filter, the record is returned. If it does not match the WHERE clause, no record is returned.
Sample code:
Apex Controller:
public class SOSLController {
public static List < List < SObject > > searchAccountContactLead( String strSearch ) {
String searchQuery = 'FIND \'' + strSearch + '*\' IN ALL FIELDS RETURNING Account( Id, Name WHERE Industry = \'Apparel\' ), Contact, Lead';
return search.query( searchQuery );
}
}
Test class:
@isTest
private class SOSLControllerTest {
static testMethod void testSOSL() {
Account acc = new Account( Name = 'Testing', Industry = 'Banking' );
insert acc;
List < List < SObject > > searchResults = SOSLController.searchAccountContactLead( 'Sample' );
List < Account > listAccount = searchResults.get( 0 );
system.assertEquals( 0, listAccount.size() );//Size will be zero since setFixedSearchResults is not set
Id [] fixedSearchResults = new Id[1];
fixedSearchResults[0] = acc.Id;
Test.setFixedSearchResults( fixedSearchResults );
searchResults = SOSLController.searchAccountContactLead( 'Sample' );
listAccount = searchResults.get( 0 );
system.assertEquals( 0, ( (List<Account>)searchResults.get( 0 ) ).size() );//Size will be still zero since WHERE condition fails for account
acc.Industry = 'Apparel';
update acc;
searchResults = SOSLController.searchAccountContactLead( 'Sample' );
listAccount = searchResults.get( 0 );
system.assertEquals( 1, listAccount.size() );//Size will be one since Account WHERE conditions succeeds
}
}