function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ckempckemp 

Test.setFixedSearchResults not working as expected

Hello,

I'm trying to set up a test method that looks something like this:

Code:
    static testMethod void testFunction() {

        // Make object
        MainObject mo = new MainObject();

        // Test object with integration set to true               
        Id[] testObjTrue = new Id[1];
        testObjTrue[0] = 'a0440000006f2cQAAQ';  // An object with Value__c = true
        Test.setFixedSearchResults(testObjTrue);
        mo.load();
        System.assert(true == mo.getValue());  // getValue() just returns this.value
    }

    public void load() {

        boolean value =
            [select Value__c
                from Main_Object__c where Name = 'MO-0000'].Value__c;
        this.value = value;
    }

As you can see from the code above, I want

However, the assertion is failing, because it's actually getting the object with Name = MO-0000 in load() (where Value__c = false) instead of using my fixed search result that I'm setting in the test method (where Value__c = true as expected).  I want to be able to do the testing without having to change MO-0000 and alter existing data.  Am I doing something wrong?  How can I do this?
jeremyfrey1jeremyfrey1
I think setFixedSearchResults (which I didn't know existed until your post) is limited to SOSL.  Since your class is using SOQL, the results aren't being limited.

Hey Salesforce -- setFixedSearchResults is a great new addition, but why doesn't it work with SOQL?  Now we're all going to have to start using SOSL instead ;)
SuperfellSuperfell
setFixedSearchResults exists because search indexing is asynchronous, making it almost impossible to write a realible test that uses SOSL without it.

standard CRUD operations/Query are all synchronous and so don't have the same problem.
ckempckemp
Thanks for your help on this, guys!

My workaround for this was to do this at the beginning of each test:

Code:
// Wipe out table for setting up clean slate
for (My_Object__c obj :
    [select Id from My_Object__c]) {
    delete obj;
}

// Insert test data here...

The data in the table gets reset after the test case finishes, so it doesn't wipe out production data, but still provides the ability to keep test data controlled for repeatability.
Scott.MScott.M
Is there a solution to this other than deleting records in the test context ?