Salesforce Certified Platform Developer II free question 7 / 10 · Domain 4: Testing, Debugging, and Deployment
In a test for a process that searches accounts with SOSL, the account created in the test does not appear in the search results. Which statement matches the documentation?
- SOSL in a test returns data that already exists in the org, so use setFixedSearchResults to set the IDs to return
- Adding @isTest(SeeAllData=true) makes the records created in the test appear in the search
- Building the search index takes time, so search again after Test.stopTest()
- SOSL in a test returns empty results, so use setFixedSearchResults to set the IDs to return
Show the answer and explanation
Answer: D
Why this is correct
The "Adding SOSL Queries to Unit Tests" page says that, to ensure test methods always behave in a predictable way, any SOSL query added to a test method returns an empty set of search results when the test method executes. To return a non-empty result, 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 that list of IDs.
Why the other options are wrong
"Building the search index takes time, so search again after Test.stopTest()" … The page says the SOSL query returns an empty set of results by design, so that test methods behave predictably. Waiting for an index or searching again after stopTest doesn't change that.
"Adding @isTest(SeeAllData=true) makes the records created in the test appear in the search" … The empty result is not caused by what data the test can see. The page says SOSL in a test method returns an empty set of results, and the way to get results is Test.setFixedSearchResults.
"SOSL in a test returns data that already exists in the org, so use setFixedSearchResults to set the IDs to return" … The page says a SOSL query in a test returns an empty set of results, not the org's existing data. The IDs you get back are the ones you specify with setFixedSearchResults.
Details worth remembering
A test method can call Test.setFixedSearchResults multiple times to define different result sets for different SOSL queries. If you don't call it, or call it without a list of record IDs, any SOSL queries later in the test method return an empty list of results.