+ Start a Discussion
Linda Bliss devLinda Bliss dev 

Need help with test code please

I used the code that Jeff Douglas http://blog.jeffdouglas.com/2010/07/13/building-a-dynamic-search-page-in-visualforce/ wrote to create a case search but cannot get the test code to work. 

Here is the controller:
public with sharing class CaseSearchController {

  // the soql without the order and limit
  private String soql {get;set;}
  // the collection of cases to display
  public List<Case> cases {get;set;}

  // the current sort direction. defaults to asc
  public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }

  // the current field to sort by. defaults to caseNumber
  public String sortField {
    get  { if (sortField == null) {sortField = 'caseNumber'; } return sortField;  }
    set;
  }

  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 40'; }
    set;
  }

  // init the controller and display some sample data when the page loads
  public CaseSearchController() {
    soql = 'select casenumber,Business_Unit__c , Site_Account__r.name, product_family__c from case where casenumber != null';
    runQuery();
  }

  // toggles the sorting of query from asc<-->desc
  public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    runQuery();
  }

  // runs the actual query
  public void runQuery() {

    try {
      cases = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 40');
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }

  }

  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {

    String caseNumber = Apexpages.currentPage().getParameters().get('caseNumber');
    String bu = Apexpages.currentPage().getParameters().get('bu');
    String accountSite = Apexpages.currentPage().getParameters().get('accountSite');
    String productFamily = Apexpages.currentPage().getParameters().get('productFamily');

    soql = 'select CaseNumber, Business_Unit__c, Site_Account__r.name, product_family__c from case where casenumber != null';
    if (!caseNumber.equals(''))
      soql += ' and caseNumber LIKE \''+String.escapeSingleQuotes(caseNumber)+'%\'';
    if (!bu.equals(''))
      soql += ' and Business_Unit__c = \''+bu+'\'';
    if (!accountSite.equals(''))
      soql += ' and Site_Account__r.name LIKE \''+String.escapeSingleQuotes(accountSite)+'%\'';  
    if (!productFamily.equals(''))
      soql += ' and product_family__c = \''+productFamily+'\'';

    // run the query again
    runQuery();

    return null;
      }

  // use apex describe to build the picklist values
  public List<String> productfamilies {
    get {
      if (productfamilies == null) {

        productfamilies = new List<String>();
        Schema.DescribeFieldResult field = Case.product_family__c.getDescribe();

        for (Schema.PicklistEntry f : field.getPicklistValues())
          productfamilies.add(f.getLabel());

      }
      return productfamilies;          
    }
    set;
  }
  public List<String> businessunits {
    get {
      if (businessunits == null) {

        businessunits = new List<String>();
        Schema.DescribeFieldResult field = Case.Business_Unit__c.getDescribe();

        for (Schema.PicklistEntry f : field.getPicklistValues())
          businessunits.add(f.getLabel());

      }
      return businessunits;          
    }
    set;
  }
 }

Here is the page:
<apex:page controller="CaseSearchController" sidebar="false">

  <apex:form >
  <apex:pageMessages id="errors" />

  <apex:pageBlock title="Case Search" mode="edit">

  <table width="100%" border="0">
  <tr>  
    <td width="200" valign="top">

      <apex:pageBlock title="Parameters" mode="edit" id="criteria">

      <script type="text/javascript">
      function doSearch() {
        searchServer(
          document.getElementById("caseNumber").value,
          document.getElementById("bu").options[document.getElementById("bu").selectedIndex].value,
          document.getElementById("accountSite").value,
          document.getElementById("productFamily").options[document.getElementById("productFamily").selectedIndex].value
          );
      }
      </script> 

      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
          <apex:param name="caseNumber" value="" />
          <apex:param name="bu" value="" />
          <apex:param name="accountSite" value="" />
          <apex:param name="productFamily" value="" />
      </apex:actionFunction>

      <table cellpadding="2" cellspacing="2">
      <tr>
        <td style="font-weight:bold;">Case Number<br/>
        <input type="text" id="caseNumber" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">BU<br/>
          <select id="bu" onchange="doSearch();">
            <option value=""></option>
            <apex:repeat value="{!businessunits}" var="bus">
              <option value="{!bus}">{!bus}</option>
            </apex:repeat>
          </select>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Site Account<br/>
        <input type="text" id="accountSite" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Product Family<br/>
          <select id="productFamily" onchange="doSearch();">
            <option value=""></option>
            <apex:repeat value="{!productfamilies}" var="prod">
              <option value="{!prod}">{!prod}</option>
            </apex:repeat>
          </select>
        </td>
      </tr>
      </table>

      </apex:pageBlock>

    </td>
    <td valign="top">

    <apex:pageBlock mode="edit" id="results">

        <apex:pageBlockTable value="{!cases}" var="case">

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Case Number" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="caseNumber" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>                
            <apex:outputLink value="/{!Case.Id}" target="_blank">{!Case.casenumber}</apex:outputLink>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="BU" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Business_Unit__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!case.Business_Unit__c}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Site Account" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Site_Account__r.name" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!case.Site_Account__r.name}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Product Family" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Product_Family__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!case.Product_Family__c}"/>
            </apex:column>

        </apex:pageBlockTable>

    </apex:pageBlock>

    </td>
  </tr>
      </table>

  <apex:pageBlock title="Debug - SOQL" id="debug">
      <apex:outputText value="{!debugSoql}" />           
  </apex:pageBlock>   

  </apex:pageBlock>

  </apex:form>

</apex:page>

Here is the test code that I am trying to use, the error is "Error: Compile Error: Variable does not exist: sources at line 25 column 15" and the line it is referring to is "testSources = controller.sources;"
@isTest 

private class theCaseSearchController { 
static testMethod void testSearchController() { 

//instantiate a page      

PageReference pg = Page.Case_Search_auto; 
Test.setCurrentPage(pg); 
pg.getParameters().put('caseNumber', '999999'); 
pg.getParameters().put('bu', 'test MC'); 
pg.getParameters().put('accountSite', 'test acct site'); 
pg.getParameters().put('productFamily', 'test prod family'); 

// instantiate the controller 

CaseSearchController controller=new CaseSearchController(); 
System.assert(controller.runSearch() == null); 
String testDebugSoql = controller.debugSoql; 

controller.toggleSort(); 
System.assertequals (controller.sortDir, 'desc'); 

List<String> testSources = new List<String>(); 
testSources = controller.sources; 
System.assertequals (testSources[0], 'vesta');

//to test the catch clause we need to make the query fail 
 

controller.sortField = 'badfield'; 
controller.runQuery(); 
}
}
Any help is greatly apprechiated!!
Thanks, Linda

 
Best Answer chosen by Linda Bliss dev
Sumitkumar_ShingaviSumitkumar_Shingavi
Hello Lindev,

I think you need to create test data in your test class. I have cleaned your test class for standard practices and you can take it ahead. I think below code will also give you good test coverage.
 
@isTest(SeeAllData=FALSE)
private class theCaseSearchController { 
		
	static testMethod void testSearchController() { 
		
		//Create Account Record
		Account accInstance = new Account(Name = 'test acct site');
		insert accInstance;
		
		//Create Case Record
		Case caseInstance = new Case(CaseNumber = '999999', 
			Business_Unit__c = 'test', //ideally this value should be actual picist value in BU picklist		
			Site_Account__c = accInstance.Id,
			product_family__c = 'test');
		insert caseInstance;
	
		//Instantiate a page
		PageReference pg = Page.Case_Search_auto;
		pg.getParameters().put('caseNumber', '999999'); 
		pg.getParameters().put('bu', 'test MC'); 
		pg.getParameters().put('accountSite', 'test acct site'); 
		pg.getParameters().put('productFamily', 'test prod family'); 
		Test.setCurrentPage(pg); 
		
		Test.startTest();
		
		// instantiate the controller
		CaseSearchController controller = new CaseSearchController(); 
		System.assert(controller.runSearch() == null); 
		String testDebugSoql = controller.debugSoql; 

		controller.toggleSort(); 
		System.assertequals (controller.sortDir, 'desc'); 

		List<String> testSources = new List<String>(); 
		testSources = controller.sources; 
		System.assertequals (testSources[0], 'vesta');

		//to test the catch clause we need to make the query fail
		controller.sortField = 'badfield'; 
		controller.runQuery();
		
		Test.stopTest();
	}
}

You might need to add some more field values as per your validation rules in org. on Account and Case OR required fields too.

Hope this helps! If yes, then mark it as solution or let me know if you need any more assistance with same.
 

All Answers

surasura
As the error message states there is no varaible with name sources in CaseSearchController 
Sumitkumar_ShingaviSumitkumar_Shingavi
Hello Lindev,

I think you need to create test data in your test class. I have cleaned your test class for standard practices and you can take it ahead. I think below code will also give you good test coverage.
 
@isTest(SeeAllData=FALSE)
private class theCaseSearchController { 
		
	static testMethod void testSearchController() { 
		
		//Create Account Record
		Account accInstance = new Account(Name = 'test acct site');
		insert accInstance;
		
		//Create Case Record
		Case caseInstance = new Case(CaseNumber = '999999', 
			Business_Unit__c = 'test', //ideally this value should be actual picist value in BU picklist		
			Site_Account__c = accInstance.Id,
			product_family__c = 'test');
		insert caseInstance;
	
		//Instantiate a page
		PageReference pg = Page.Case_Search_auto;
		pg.getParameters().put('caseNumber', '999999'); 
		pg.getParameters().put('bu', 'test MC'); 
		pg.getParameters().put('accountSite', 'test acct site'); 
		pg.getParameters().put('productFamily', 'test prod family'); 
		Test.setCurrentPage(pg); 
		
		Test.startTest();
		
		// instantiate the controller
		CaseSearchController controller = new CaseSearchController(); 
		System.assert(controller.runSearch() == null); 
		String testDebugSoql = controller.debugSoql; 

		controller.toggleSort(); 
		System.assertequals (controller.sortDir, 'desc'); 

		List<String> testSources = new List<String>(); 
		testSources = controller.sources; 
		System.assertequals (testSources[0], 'vesta');

		//to test the catch clause we need to make the query fail
		controller.sortField = 'badfield'; 
		controller.runQuery();
		
		Test.stopTest();
	}
}

You might need to add some more field values as per your validation rules in org. on Account and Case OR required fields too.

Hope this helps! If yes, then mark it as solution or let me know if you need any more assistance with same.
 
This was selected as the best answer
Sumitkumar_ShingaviSumitkumar_Shingavi
Also remove unused and non-existing variables. I gave you a prototype which you can take ahead and mold it as per your need.
surasura

As the error message states there is no varaible with name sources in CaseSearchController , colund you kindly clarify what you are trying to access from controller.sources 
Linda Bliss devLinda Bliss dev
I was able to take Sumitkumar's test code and change a couple of things to get it to work with 85% coverage.  I changed the "Source" reference to "productfamilies."  This is my first attempt at developing a page and code.

I have to add several fields once I get the list so hope to incorporate into the page and controllers without issue. 

I may be needing more help if I run in the near future :-).  Thanks for both of your help!!  Linda
 
@isTest(SeeAllData=FALSE) 

private class theCaseSearchController {  
static testMethod void testSearchController() {  

//Create Account Record 
Account accInstance = new Account(Name = 'test acct site'); 
insert accInstance; 

//Create Case Record 
Case caseInstance = new Case(
Business_Unit__c = 'TSC', 
Site_Account__c = accInstance.Id, 
product_family__c = '1A2'); 
insert caseInstance; 

//Instantiate a page 
PageReference pg = Page.Case_Search_auto; 
pg.getParameters().put('caseNumber', '999999');  
pg.getParameters().put('bu', 'TSC');  
pg.getParameters().put('accountSite', '001i000000czKEdAAM');  
pg.getParameters().put('productFamily', '1A2');  
Test.setCurrentPage(pg);  
Test.startTest(); 

// instantiate the controller 

CaseSearchController controller = new CaseSearchController();  
System.assert(controller.runSearch() == null);  
String testDebugSoql = controller.debugSoql;  

controller.toggleSort();  
System.assertequals (controller.sortDir, 'desc');  

List<String> testSources = new List<String>();  
testSources = controller.productfamilies;  
System.assertequals (testSources[0], '1A2'); 

//to test the catch clause we need to make the query fail 
controller.sortField = 'badfield';  
controller.runQuery(); 
Test.stopTest(); 

} 

}