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
ChiyanChiyan 

how to write a test code for search functionality

Hi 
here is the code


Public with sharing class KeywordSearch{
 Public List<Opportunity> optyList {get;set;}
 Public List<contact> conList{get;set;}
 Public List<account> accList{get;set;}

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

  Public void soslSearchmethod (){
   optyList = New List<Opportunity>();
   conList = New List<contact>();
   accList = New List<account>();
   if(searchStr.length() > 2){
   String searchStr1 = '*'+searchStr+'*';
   String searchQuery = 'FIND \'' + searchStr1 + '\' IN ALL FIELDS RETURNING  Account (Id,Name,type),Contact(name,email),Opportunity(name,StageName)';
   List<List <sObject>> searchList = search.query(searchQuery);
   accList = ((List<Account>)searchList[0]);
   conList  = ((List<contact>)searchList[1]);
   optyList = ((List<Opportunity>)searchList[2]);
   if(accList.size() == 0 && conList.size() == 0 && optyList.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 three characters..'));
   return;
   }
  }
}
Best Answer chosen by Chiyan
Raj VakatiRaj Vakati
Try this
 
@isTest
private class KeywordSearchTesr {
    static testmethod void testSeacrh(){
        Account acc =new Account( Name = 'test' ,type='custmer' ); 
        insert acc;
      
  Contact c=new Contact(
            FirstName='test',
            LastName = 'lname',
            Email = 'email@gmail.com',AccountId = acc.Id ,
            Phone = '9743800309'); 
        insert c; 
		
		
	  Opportunity opp = new Opportunity();
        opp.StageName = 'Sourcing Demand';
        opp.AccountId = acc.id;
        opp.CloseDate =  System.today();
        opp.Name = 'test';
        insert opp;
       
      KeywordSearch sea = new KeywordSearch() ;
	  sea.searchStr='test';
	  sea.soslSearchmethod ();
	  
	  
            }
			
	static testmethod void testSeacrh2(){
        
       
      KeywordSearch sea = new KeywordSearch() ;
	  sea.searchStr='test';
	  sea.soslSearchmethod ();
	  
	  
            }
}