1

I am having trouble working out how to get my SOSL search page to test with a solid percentage.  The reason I am using SOSL is because of the Long Text Areas that I am searching through.

Here is my Controller:

Public with sharing class SOSLController{
Public List<Journal_Entry__c> entList {get;set;}

Public String searchStr{get;set;}
Public SOSLController(){
}

Public void soslDemo_method(){

String userID = UserInfo.getUserId();


entList = New List<Journal_Entry__c>();
if(searchStr.length() > 1){
String searchStr1 = '*'+searchStr+'*';
String searchQuery = 'FIND \'' + searchStr1 + '\' IN ALL FIELDS RETURNING 
Journal_Entry__c (Id,Name,DateText__c,Submitted_for_Interp_Count__c,Created_Self_Interp__c,Haven__c,UserID__c 
WHERE UserID__c LIKE :userID)';
List<List <sObject>> searchList = search.query(searchQuery);
entList = ((List<Journal_Entry__c>)searchList[0]);
if(entList.size() == 0){
   apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Sory, no results returned with matching string..'));
   return;
}
}
else{
apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Please   enter at least two characters..'));
   return;
   }
  }
}

And this is what I have so far with my Test... You will notice that I give the userID string a user Id that works in my VF pages for the test I'm trying to do, but in the Controller, this Id is captured from the active user.

@isTest
public class TestSOSLController{ 

public static testMethod void testSoslFixedResults() {

 PageReference myVfPage = Page.MyJournal;
 Test.setCurrentPage(myVfPage);

 SOSLController testCont = new SOSLController();

 String userID = '00555000001R62HAAS';

   Id [] fixedSearchResults= new Id[1];
   fixedSearchResults[0] = 'a0955000001ODaU';
   Test.setFixedSearchResults(fixedSearchResults);
   List<List<SObject>> searchList = [FIND 'test' 
                                     IN ALL FIELDS RETURNING 
                                        Journal_Entry__c(Id,Name,DateText__c,Submitted_for_Interp_Count__c,Created_Self_Interp__c,Haven__c,UserID__c 
                                                         WHERE UserID__c     LIKE :userID LIMIT 1)];


        system.assert(searchList != null);
    }
}

I understand that SOSL has a special syntax to be used when Testing, based on this page "Adding SOSL Queries to Unit Tests" and you will see that I have attempted to use this, but I am obviously failing misserably.  

I would greatly appreciate any help I can get!

3

This is a database isolation problem. Here, you're trying to set your search results to a hard-coded ID value, but you haven't specified SeeAllData=true, so your code cannot see that record, which results in no values coming back in the search results.

Instead, create a new record, and set that Id value in the fixed search results:

Journal_Entry__c je = new Journal_Entry__c();
insert je;
fixedSearchResults[0] = je.Id;
Test.setFixedSearchResults(fixedSearchResults);

I might also add, you have a SOSL injection problem. Don't use dynamic search queries when you don't need to:

Public with sharing class SOSLController{
    Public List<Journal_Entry__c> entList {get;set;}

    Public String searchStr{get;set;}
    Public SOSLController(){
    }

    Public void soslDemo_method(){
        if(searchStr.length() < 2)
        {
            apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Please   enter at least two characters..'));
        } else {
            String searchStr1 = '*'+searchStr+'*';
            List<List <sObject>> searchList = [FIND :searchStr1 IN ALL FIELDS RETURNING 
                                               Journal_Entry__c (Id,Name,DateText__c,Submitted_for_Interp_Count__c,Created_Self_Interp__c,Haven__c,UserID__c 
                                                                 WHERE UserID__c LIKE :UserInfo.getUserId())];
            entList = ((List<Journal_Entry__c>)searchList[0]);
            if(entList.size() == 0){
                apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Sory, no results returned with matching string..'));
            }
        }            
    }
}
| improve this answer | |
  • Thank you so much sfdcfox , your improvements upon the actual controller are really nice... Much cleaner. I created a new controller with your code, and then made a new Test that incorporated your suggestions, and it works, but only covers 8%. Could you offer some help to bring the % up? – anotherSFguy Mar 24 '16 at 20:04
  • @anotherSFguy See cropredy's answer-- it should get you pretty close in coverage. – sfdcfox Mar 24 '16 at 21:18
1

Here is an approach to getting test coverage and assertions; @sfdcfox comments are of course, valid.as well

@isTest
private static void testSoslController() {

  Journal_Entry__c[] jeList = new List<Journal_Entry__c> {new Journal_Entry__c( set your values),
                                                 new Journal_Entry__c ( set your values)
  };
  insert jeList;   // mock test objects

  SOSLController ctlr = new SOSLController();
  ctrl.searchStr = 'foo';                       
  System.assertEquals('foo',ctlr.searchStr); // tests getter/setter

  Test.setFixedSearchResults(new List<ID>{jeList[0].id});
  ctlr.soslDemoMethod();    // invoke the search logic - with at least 1 guaranteed result
  system.assertEquals(false,ApexPages.hasMessages(),'sb no errors');

  Test.setFixedSearchResults(new List<ID>());
  ctlr.soslDemoMethod();    // invoke the search logic - with at least 1 guaranteed result
  system.assert(ApexPages.getMessages()[0].getSummary().contains('no results returned'),ApexPages.hasMessages() 
                                                                                 ? ApexPages.getMessages()[0].getSummary() 
                                                                                 : 'sb error');

  ctrl.searchStr = 'f'; 
  Test.setFixedSearchResults(new List<ID>{jeList[0].id});
  ctlr.soslDemoMethod();    // invoke the search logic - too short a string
  system.assert(ApexPages.getMessages()[1].getSummary().contains('at least two'),ApexPages.hasMessages() 
                                                                                ? ApexPages.getMessages()[ApexPages.getMessages().size()-1].getSummary() 
                                                                                : 'sb search str error');


}
| improve this answer | |
  • Thank you so much cropedy, I have some questions regarding your code... I'm still learning the coding aspect of SF. In creating a new jeList, I would assume that the two fields that I need to set are the Name and the UserID__c that I use to compare to the active User, but what would that look like? This is being done in SF Communities and when I simply "Preview" the page as the Admin, I don't see the page... I have to log in to the community as the user for real testing purposes... so, how do I get the User Id? – anotherSFguy Mar 24 '16 at 20:10
  • (1) Just use UserInfo.getUserId() - since this is a testmethod with static SOSL results, the actual user isn't important so the running user is fine; (2) as for other fields on Journal_Entry__c - any other required field (if name is auto-number, you don't even/can't set that); (3) note also that I just typed in the code and there could be typos – cropredy Mar 24 '16 at 22:55
0

Thank you all for your fantastic help! I chose @sfdcfox answer because of the help in cleaning up my actual controller, but I learned so much from both answers. In the end, I am using a combination of answers found both here and on the Salesforce Developer Forum.

Here is my test, which covers 91% when using @sfdcfox version of my controller.

@isTest (SeeAllData=true)
public class TestSOSLController
{ 


public static testMethod void testSoslFixedResults() 
{

    Account acc = [Select Id FROM Account Where Name ='Testing'];

    Contact cont = new Contact();
        cont.FirstName = 'TheTest';
        cont.LastName = 'Tester';
        cont.AccountId = acc.Id;
    insert cont;

    Journal_Profile__c jp = new Journal_Profile__c();
    jp.UserID__c = UserInfo.getUserId();
    jp.Contact__c = cont.Id;
    insert jp;

    Journal_Entry__c je = new Journal_Entry__c();
    je.Name = 'Test';
    je.UserID__c = UserInfo.getUserId();
    je.Journal_Profile__c = jp.Id;
    // Add all required Field here
    insert je;

    PageReference myVfPage = Page.MyJournal;
    Test.setCurrentPage(myVfPage);

    Id [] fixedSearchResults = new Id[]{je.Id};
    Test.setFixedSearchResults(fixedSearchResults);

        SOSLController testCont = new SOSLController();
        testCont.searchStr='';
        testCont.soslDemo_method();

        testCont.searchStr='Test';
        testCont.soslDemo_method();
        // System.assert( testCont.entList  != null);
}

public static testMethod void testNonResults() 
{

    Account acc = [Select Id FROM Account Where Name='Testing'];

    Contact cont = new Contact();
        cont.FirstName = 'TheTest2';
        cont.LastName = 'Tester2';
        cont.AccountId = acc.Id;
    insert cont;

    Journal_Profile__c jp = new Journal_Profile__c();
    jp.UserID__c = UserInfo.getUserId();
    jp.Contact__c = cont.Id;
    insert jp;

    Journal_Entry__c je = new Journal_Entry__c();
    je.Name = 'Test';
    je.UserID__c = UserInfo.getUserId();
    je.Journal_Profile__c = jp.Id;
    // Add all required Field here
    insert je;

    PageReference myVfPage = Page.MyJournal;
    Test.setCurrentPage(myVfPage);

    Id [] fixedSearchResults = new Id[]{je.Id};
    Test.setFixedSearchResults(fixedSearchResults);

    SOSLController testCont = new SOSLController();

    testCont.searchStr='Demo';
    testCont.soslDemo_method();
}

}

Again, Thank you all very much! I really learned so much in the last 24 hours!

| improve this answer | |

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.