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
aressaress 

test class for VFpage

Can anyone provide test class for following VF PAGE . The requirement is to search text in account,,contact,lead.
Please Include minimum 5 Asserts and test cases for positive negative bulk scenarios.

-------------------------------------------------VF--------------------------------------------
<apex:page Controller="SOSLController">
  <apex:form >
    <apex:inputText value="{!searchStr}"/>
    <apex:commandButton value="Search in Account, Contact, Opportunity" action="{!search}" reRender="accountId,error,opportunityId,contactId" status="actStatusId"/>
    <apex:actionStatus id="actStatusId">
      <apex:facet name="start" >
      <img src="/img/loading.gif"/>                    
      </apex:facet>
    </apex:actionStatus>
  </apex:form>
    
  <apex:outputPanel title="" id="error">
    <apex:pageMessages ></apex:pageMessages>
  </apex:outputPanel>
  
  
  <apex:pageBlock title="Accounts" id="accountId">
    <apex:pageblockTable value="{!accountList }" var="accountVar">
      <apex:column value="{!accountVar.name}"/>
      <apex:column value="{!accountVar.Type}"/>
    </apex:pageblockTable>
  </apex:pageBlock>

  
 
  <apex:pageBlock title="Contacts" id="contactId">
    <apex:pageblockTable value="{!contactList}" var="contactVar">
      <apex:column value="{!contactVar.name}"/>
      <apex:column value="{!contactVar.email}"/>
    </apex:pageblockTable>
  </apex:pageBlock>
  
  
      
  
  <apex:pageBlock title="Opportunities" id="opportunityId">
    <apex:pageblockTable value="{!OpportunityList}" var="opportunityVar">
      <apex:column value="{!opportunityVar.name}"/>
      <apex:column value="{!opportunityVar.StageName}"/>
    </apex:pageblockTable>
  </apex:pageBlock>
</apex:page>
-------------------------------------------------Controller------------------------------------------

Public with sharing class SOSLController{
  Public List<Opportunity> OpportunityList {get;set;}
  Public List<contact> contactList{get;set;}
  Public List<account> accountList{get;set;}
    
  Public String searchStr{get;set;}
    Public SOSLController(){
    }
    /**
    Method:searchText 
    Description : Method use SOSL Query to search the text.
    @return : searchText or Error Message */
    Public List<List<sObject>> search(){
      OpportunityList = New List<Opportunity>();
      contactList = New List<contact>();
      accountList = New List<account>();
     
      String searchStr1 = '*'+searchStr+'*';
      String searchQuery = 'FIND \'' + searchStr1 + '\' IN Name FIELDS RETURNING  Account (Id,Name,type),Contact(name,email),Opportunity(name,StageName)';
      List<List <sObject>> searchList = search.query(searchQuery);
      accountList = ((List<Account>)searchList[0]);
      contactList  = ((List<contact>)searchList[1]);
      OpportunityList = ((List<Opportunity>)searchList[2]);
      if(accountList.size() == 0 && contactList.size() == 0 && OpportunityList.size() == 0){
          apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Sory, no results returned with matching string..'));
          
      }
    return searchList;
    }
}
Best Answer chosen by aress
Amit Chaudhary 8Amit Chaudhary 8
Hi Aylsha,

Some important tips for SOSL query in Unit Test :-
Adding SOSL Queries to Unit Tests

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. All SOSL queries that take place later in the test method return the list of record IDs that were specified by the Test.setFixedSearchResults method

Update your test class like below
@isTest
public class SOSLControllerTest
{ 
	public static testMethod void testSoslFixedResults() 
	{
		Account testAcct = new Account (Name = 'Test',type='Customer');
		insert testAcct;

		Contact con = new Contact();
			con.LastName='Test';
			con.FirstName ='Test';
			con.accountid = testAcct.id;
			con.Email='asasdas@gmail.com'
		insert con;
	
		// Creates first opportunity
		Opportunity oppt = new Opportunity(Name ='Test',
							AccountID = testAcct.ID,
							StageName = 'Customer Won',
							Amount = 3000,
							CloseDate = System.today());
		Insert oppt;
		
		Test.StartTest();
			Id [] fixedSearchResults= new Id[3];
				fixedSearchResults[0] = testAcct.Id;
				fixedSearchResults[1] = con.Id;
				fixedSearchResults[2] = oppt.Id;
			Test.setFixedSearchResults(testAcct.Id);

			
			SOSLController testCont = new SOSLController();
			testCont.searchStr = 'Test';
			testCont.search();		
			system.assert(testCont.accountList != null);
		Test.StopTest();

    }
}
I will recommend you to start using trailhead to learn about test classes
1) https://trailhead.salesforce.com/modules/apex_testing

Pleasse check below post sample test class
1) http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html

Also please check below post
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm
2) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_example.htm

Let us know if this will help you

Thanks
 

All Answers

Raj VakatiRaj Vakati
@isTest
public class TestSOSLController{ 

public static testMethod void testSoslFixedResults() {


Account testAcct = new Account (Name = 'My Test Account',type='Customer');
     insert testAcct;
	 Contact con = new COntact();
	 con.LastName='Test';
	 con.Email='asasdas@gmail.com'

    // Creates first opportunity
    Opportunity oppt = new Opportunity(Name ='New mAWS Deal',
                            AccountID = testAcct.ID,
                            StageName = 'Customer Won',
                            Amount = 3000,
                            CloseDate = System.today());
							
 PageReference myVfPage = Page.YOURPAGE;
 Test.setCurrentPage(myVfPage);

 SOSLController testCont = new SOSLController();


   Id [] fixedSearchResults= new Id[1];
   fixedSearchResults[0] = testAcct.Id;
   Test.setFixedSearchResults(testAcct.Id);
   List<List<SObject>> searchList = [FIND 'test' 
                                     IN ALL FIELDS RETURNING  Account (Id,Name,type),Contact(name,email),Opportunity(name,StageName)';)];


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

 
aressaress
Thanks
 
Amit Chaudhary 8Amit Chaudhary 8
Hi Aylsha,

Some important tips for SOSL query in Unit Test :-
Adding SOSL Queries to Unit Tests

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. All SOSL queries that take place later in the test method return the list of record IDs that were specified by the Test.setFixedSearchResults method

Update your test class like below
@isTest
public class SOSLControllerTest
{ 
	public static testMethod void testSoslFixedResults() 
	{
		Account testAcct = new Account (Name = 'Test',type='Customer');
		insert testAcct;

		Contact con = new Contact();
			con.LastName='Test';
			con.FirstName ='Test';
			con.accountid = testAcct.id;
			con.Email='asasdas@gmail.com'
		insert con;
	
		// Creates first opportunity
		Opportunity oppt = new Opportunity(Name ='Test',
							AccountID = testAcct.ID,
							StageName = 'Customer Won',
							Amount = 3000,
							CloseDate = System.today());
		Insert oppt;
		
		Test.StartTest();
			Id [] fixedSearchResults= new Id[3];
				fixedSearchResults[0] = testAcct.Id;
				fixedSearchResults[1] = con.Id;
				fixedSearchResults[2] = oppt.Id;
			Test.setFixedSearchResults(testAcct.Id);

			
			SOSLController testCont = new SOSLController();
			testCont.searchStr = 'Test';
			testCont.search();		
			system.assert(testCont.accountList != null);
		Test.StopTest();

    }
}
I will recommend you to start using trailhead to learn about test classes
1) https://trailhead.salesforce.com/modules/apex_testing

Pleasse check below post sample test class
1) http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html

Also please check below post
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm
2) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_example.htm

Let us know if this will help you

Thanks
 
This was selected as the best answer