+ Start a Discussion
yarramyarram 

how to write test class for this Controller class

Hi All,

i am not able to cover getter method "if " statement code in my test class

how to write test class for this Controller class List variable getter method "if" satatement 

public with sharing class listtestCtrl {
public String selectedType{get;set;}
public String selectedLeadSource{get;set;}
 
public List<Opportunity> listOpp{
    get{
        String query='Select id,LeadSource,Name,StageName,Type from Opportunity ';
       
        if((this.selectedLeadSource!='All Sources') && (this.selectedLeadSource!= null)){
            query=query+'Where LeadSource=:selectedLeadSource';
        }

       if((this.selectedType!='All Types') && (this.selectedType!= null)){
            query=query+'AND Type=:selectedType';
        } 

query += ' ORDER BY LeadSource';
         return (List<Opportunity>)database.query(query);  
    }
    set;
}

}

Please help me .
Thanks in advance.
Thanks,
Yarram
Best Answer chosen by yarram
bob_buzzardbob_buzzard
You'll need to set a value into the selectedLeadSource and selectedtype properties prior to calling the listOpp method - something like:

ListTestCtrl controller =new ListTestCtrl();
controller.selectedLeadSource='Web';
controller.selectedType='Prospect';
List<Opportunity> opps=controller.listOpp();

// do some asserts here for the return list of opps


All Answers

bob_buzzardbob_buzzard
You'll need to set a value into the selectedLeadSource and selectedtype properties prior to calling the listOpp method - something like:

ListTestCtrl controller =new ListTestCtrl();
controller.selectedLeadSource='Web';
controller.selectedType='Prospect';
List<Opportunity> opps=controller.listOpp();

// do some asserts here for the return list of opps


This was selected as the best answer
Jen BennettJen Bennett
You should be able to set the variable once you have instantiated the controller in the test. So you would probably have something like the following: 
listtestCtrl controller = new listtestCtrl();
controller.selectedLeadSource = 'Not All Sources';
controller.selectedType = 'Not All Types';
List<Opportunity> oppsList = controller.listOpp();

yarramyarram
Thank you very much bob_buzzard and JJbennett530...... its working and Coverd.