I'm new to salesforce, but have been given a task that I am puzzled on. I am given a test class with an @testSetup method which inserts relevant data for the test methods. In my test method, SOQL calls works, but SOSL does not, whereas if I run SOSL calls in the @testSetup method, it works fine. I am thinking this is a problem of scope, but I don't know how to pass the relevant data to my test methods (I tried making fixedSearchResults global but that didn't work). Example code below:
@isTest
private class Test_Class {
@testSetup static void initializeData() {
Account acct = new Account(Name = 'Acme');
insert acct;
list<id> fixedSearchResults = new list<id>();
fixedSearchResults.add(acct.Id);
Test.setFixedSearchResults(fixedSearchResults);
//SOSL -- works as expected
List<List<sObject>> testAccountList2 = [FIND 'test'
IN ALL FIELDS RETURNING
Account(name, id WHERE name = 'Acme')];
System.debug(testAccountList2[0][0].Id);
System.debug(testAccountList2[0][0].get('Name'));
//SOQL -- Works as expected
Account acct2 = [SELECT Name FROM Account WHERE Name='Acme' LIMIT 1];
System.debug(acct2);
}
static testMethod void testingMethod() {
test.startTest();
myClass q = new myClass(); //test my class (not relevant here though)
test.stopTest();
//SOQL -- THIS WORKS
Account acct2 = [SELECT Name FROM Account WHERE Name='Acme' LIMIT 1];
System.debug(acct2);
/*
THIS WOULD MAKE THE SOSL CALL BELOW WORK, BUT DEFEATS THE PURPOSE OF THE initializeData() METHOD
Account acct = new Account(Name = 'Acme');
insert acct;
list<id> fixedSearchResults = new list<id>();
fixedSearchResults.add(acct.Id);
Test.setFixedSearchResults(fixedSearchResults);
*/
//SOSL -- Out of bounds... Nothing is grabbed.
List<List<sObject>> testAccountList2 = [FIND 'test'
IN ALL FIELDS RETURNING
Account(name, id WHERE name = 'Acme')];
System.debug(testAccountList2[0][0].Id);
System.debug(testAccountList2[0][0].get('Name'));
}
}
So how can I get the testMethod SOSL calls to work without having to repeat adding fixedSearchResults?