Tuesday, May 20, 2014

Get SOSL covered during Apex Test Execution.

Why my SOSL returning no data during testing??
I created sample data, I saw it in log.I swear but why it return no data?

Why?
Why?

The hair drop one by one...the wrinkle become finer and finer.She stay quietly facing her laptop.She did not notice that her age is multiplying hastily..

.
.
.

Stop all the drama, let see the point here.The possibility why SOSL not returning data during Apex Test Execution is because Salesforce designed it that way!

WHAT!!!

Yes, to ensure test class run in predictable way they decide to not return data when you use SOSL.
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. -more info.
Okay, so we can use this Test.setFixedSearchResults.I gave example how to use it like below.Note that it only show how we can test SOSL NOT how to implement SOSL.
@isTest
private class MyControllerTest{ 
 
    private static Account acc1;
   //set up data for each test method
    static {
      acc1 = new Account(Name='MyFatherCompany',Description__c='Produce stuff');
      insert acc1;
      System.assertEquals(1,[select count() from Account  where Name = 'MyFatherCompany' ]);
     
    }
    static testMethod void test1(){
        Test.startTest();
            //Apply the setFixedSearchResults here
             Id [] fixedSearchResults= new Id[1];
             fixedSearchResults[0] =acc1.Id;
             Test.setFixedSearchResults(fixedSearchResults);
        
              MyController obj = new MyController();
             
             obj.custname=acc1.Name;
             obj.searchUsingSOSL(); //This code is contain SOSL.
      
        
        Test.stopTest();
    }
 }

Now you will see the data, and the method that process those data should be covered and you should live happily ever after.=)

No comments:

Post a Comment