3

On doing a sosl search with just one character search parameter, I am getting an exception. To overcome this i have used custom error message in the catch block.However I am unable to cover the catch block in the test class. The functionality of the code is working fine.

CONTROLLER METHOD:
    public void Query(){
        try{
                        iserrorfound = false;

                        if (sSearchWord != null && sSearchWord.trim() != '')    
                        {     
                            List < List < sObject >> SearchResult = search.query('FIND \'' + string.escapeSingleQuotes(sSearchWord) + '\' IN ALL FIELDS RETURNING Object__c (ID,name,field1__c,field2__c '+ addlFunc() +' )');
                            belts = SearchResult[0];
                            SetController= new ApexPages.StandardSetController(SearchResult[0]);
                        } 
                        else    
                        {
                            //Logic if search parameter is null/empty
                        }
                        SetController.setPageSize(10);
        }
        catch(Exception e)
                {

                    ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Please enter at least two characters');
                    ApexPages.addMessage(myMsg);
                    iserrorfound = true;
                }

    }


TEST CLASS:

    test.starttest()
    //
     Inst.sSearchWord = 'p';
     Inst.Query();
    test.stoptest()
  • you could also test for the size of the search string before entering the SOSL query and then the catch block becomes less interesting – cropredy Feb 26 '16 at 20:51
0

SOSL is awkward to test given that you have to use Test.setFixedSearchResults and there isn't any built-in testing mechanism to help with your case.

All you can do is add code to allow the testing (generally something that should only be done as a last resort). For example:

@TestVisible private Boolean throwSearchException = false;

public void Query(){
    try {
        ...
        if (throwSearchException) throw new SearchException('Fake');
        ...
    } catch (SearchException e) {
        ...
    }
}

and then in the test case for this error condition

...
YourController inst = new YourController();
inst.throwSearchException = true;
...

and assert the ApexPages.Message that you get.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.