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
Saie Shendage 7Saie Shendage 7 

How to write test class for below apex controller?

<apex:page controller="Page3_Controller">
    <script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");
            for(var i=0; i<inputCheckBox.length; i++){
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    <apex:form >
        <apex:pageBlock >
        	<apex:pageBlockSection >
                	Society:<apex:selectList value="{!selectedSociety}" size="1">
                        <apex:selectOptions value="{!records}"/>
                    </apex:selectList>
                    
                    Year:<apex:selectList value="{!selectedYear}" size="1">
                        <apex:selectOptions value="{!years}"/>
                    </apex:selectList>
                    
                    Month:<apex:selectList value="{!selectedMonth}" size="1">
                        <apex:selectOptions value="{!months}"/>
                    </apex:selectList>
                <apex:commandButton action="{!showRecords}" value="View Defaulters" rerender="pbt"/>
                <apex:commandButton action="{!addDues}" value="Add Dues" rerender="pbt1"/>
            </apex:pageBlockSection>
            
            <apex:pageBlockSection columns="2" title="Select defaulters to send email to">
            	<apex:pageBlockTable value="{!wrapDuesList}" var="d" id="pbt" >
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                        </apex:facet>
                        <apex:inputCheckbox value="{!d.checked}" id="inputId"/>
                    </apex:column>
                  <apex:column value="{!d.due.Member_Name__c}" />
                  <apex:column value="{!d.due.Dues_Remaining__c}"/>
            </apex:pageBlockTable>
                
                <apex:pageBlockTable id="id1" value="{!checkedDues}" var="d">
            	<apex:column value="{!d.Member_Name__c}" />
                  <apex:column value="{!d.Dues_Remaining__c}"/>
            </apex:pageBlockTable>
            
            <apex:commandButton value="Show selected" action="{!showRecords}" rerender="id1"/>
            <apex:commandButton value="Send Reminder Email" action="{!sendReminderEmail}"/>
            
            
            </apex:pageBlockSection>
            
            <apex:pageBlockSection title="Add Dues">
            	<apex:pageBlockTable value="{!defaulters1}" var="d" id="pbt1">
            	<apex:column value="{!d.Member_Name__c}"/>
                <apex:column value="{!d.Total_dues__c}"/>
                <apex:column value="{!d.Dues_Remaining__c}"/>
                <apex:column headerValue="Dues Paid">                            
                	<apex:inputText value="{!d.Dues_Paid__c}" />                    
          	  	</apex:column>
            	</apex:pageBlockTable>
                <br/>
            	<apex:commandButton value="Add" action="{!add}"/>
            </apex:pageBlockSection>
            
            
        </apex:pageBlock>
    </apex:form>
</apex:page>
 
public class Page3_Controller {
	public string selectedSociety{get;set;}
    public string selectedYear{get;set;}
    public string selectedMonth{get;set;}
    
    public List<wrapDues> wrapDuesList{get;set;}
    public List<Due__c> checkedDues{get;set;}
    
   	public list<selectOption> records{get;set;}
    public list<selectOption> years{get;set;}
    public list<selectOption> months{get;set;}
    
    public list<String> yearsToAdd=new List<String>{'2015','2016','2017','2018','2019','2020','2021'};
    
    public list<String> monthsToAdd=new List<String>{'Jan','Feb','March','April','May','June','July','Aug','Sept','Oct','Nov','Dec'};
        
   	public list<Due__c> defaulters{get;set;}
    public list<Due__c> defaulters1{get;set;}
    public list<Society__c> societies;
   
   
   	public Page3_Controller(){
   
       defaulters=new List<Due__c>();
       
       records=new List<selectOption>();
       years=new List<selectOption>();
       months=new List<selectOption>();
       
       societies=[select id, name from Society__c];
        for(Society__c a:societies){
            records.add(new selectoption(a.id,a.name));
        }
        
        for(String y:yearsToAdd){
            years.add(new selectoption(y,y));
        }
        
        for(String m:monthsToAdd){
            months.add(new selectoption(m,m));
        }
        

   	}
    
    public class wrapDues{
        public Due__c due{get;set;}
        public Boolean checked{get;set;}
        public wrapDues(Due__c d){
            due=d;
            checked=false;
        }
    }
    
   public pageReference showRecords(){
       defaulters=[select id, member_name__c, dues_remaining__c,Member_Name__r.Name, Member_Name__r.Email__c, Month__c from Due__c where 
                   society_name__c=:selectedSociety and year__c=:selectedYear and month__c=:selectedMonth and dues_remaining__c>0];
       if(wrapDuesList==null){
           wrapDuesList = new List<wrapDues>();
            for(Due__c a: defaulters) {
                wrapDuesList.add(new wrapDues(a));
            }
        }
       checkedDues=new List<Due__c>();
       for(wrapDues wrapDuesObj:wrapDuesList){
           if(wrapDuesObj.checked == true) {
                checkedDues.add(wrapDuesObj.due);
            }
       }
   		return null;
   }
    
    public PageReference sendReminderEmail(){
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        for(Due__c d:checkedDues){
            if(d.Member_Name__r.Email__c!=null){
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                List<String> sendTo = new List<String>();
      			sendTo.add(d.Member_Name__r.Email__c);
      			mail.setToAddresses(sendTo);
                
                mail.setReplyTo('saie_shendage@persistent.com');
      			mail.setSenderDisplayName('Secretary of the Society');
    			mail.setSubject('Remaining Dues Not Paid');
              String body = 'Dear ' + d.Member_Name__r.Name + ', ';
              body += 'Your remaining dues are '+d.Dues_Remaining__c+' for the month of '+d.Month__c;
              body += ' Please pay the dues Asap, otherwise penalty would be added.';
              mail.setHtmlBody(body);
            
              // Step 5. Add your email to the master list
              mails.add(mail);
            }
        }
        Messaging.sendEmail(mails);
        return null;
    }
    
    public PageReference addDues(){
        defaulters1=[select id, member_name__c,Total_Dues__c, dues_remaining__c,Dues_Paid__c from Due__c where 
                   society_name__c=:selectedSociety and year__c=:selectedYear and month__c=:selectedMonth and dues_remaining__c>0];
      	return null;
    }
    
    public void add(){
        update defaulters1;
    }
    
}
I want test class for apex class Page3_Controller. Please help.
Best Answer chosen by Saie Shendage 7
Malika Pathak 9Malika Pathak 9

Hi Saie,

Please Find The Solution.  How to write test class for below apex controller?

Test Class  with 100% coverage

@isTest
public class Page3_ControllerTest {
    @isTest
    public static void page3(){
        Society__c testSoc=new Society__c();
        testSoc.Name='Some Name';
        testSoc.Reg_Code__c='12345';
        testSoc.Location__c='Some Location';
        testSoc.Formation_Year__c='2012';
        insert testSoc;
        
        member_name__c memberNameObj=new member_name__c();
        memberNameObj.Name='John';
        memberNameObj.Email__c='abc@gmail.com';
        insert memberNameObj;
        
        Due__c dueObj=new Due__c();
        dueObj.Name='check';
        dueObj.year__c=string.valueOf(Date.today().Year());    //'2021' 
        dueObj.month__c=string.valueOf(Date.today().Month());     //'1';
        dueObj.Society_Name__c=testSoc.id;
        dueObj.member_name__c=memberNameObj.Id;
        dueObj.dues_remaining__c=1000;
        insert dueObj;
        
        Due__c dueObj1=new Due__c();
        dueObj1.Name='check1';
        dueObj1.year__c=string.valueOf(Date.today().Year());    //'2021' 
        dueObj1.month__c=string.valueOf(Date.today().Month());     //'1';
        dueObj1.dues_remaining__c=1000;
        dueObj1.Society_Name__c=testSoc.id;
        dueObj1.member_name__c=memberNameObj.Id;
        insert dueObj1;
        
        test.startTest();
        Page3_Controller page3Obj=new Page3_Controller();
        page3Obj.selectedSociety=testSoc.id;
        page3Obj.selectedYear=string.valueOf(Date.today().Year());
        page3Obj.selectedMonth=string.valueOf(Date.today().Month());
        
        page3Obj.showRecords();
        page3Obj.addDues();
        page3Obj.add();
        page3Obj.sendReminderEmail();
        test.stopTest();
        
    }
}

apex class

If you do wrapDues class of checked=true then test coverage is 100%

and if you do checked=false then test coverage is 78%.

public class Page3_Controller {
	public string selectedSociety{get;set;}
    public string selectedYear{get;set;}
    public string selectedMonth{get;set;}
    
    public List<wrapDues> wrapDuesList{get;set;}
    public List<Due__c> checkedDues{get;set;}
    
   	public list<selectOption> records{get;set;}
    public list<selectOption> years{get;set;}
    public list<selectOption> months{get;set;}
    
    public list<String> yearsToAdd=new List<String>{'2015','2016','2017','2018','2019','2020','2021'};
    
    public list<String> monthsToAdd=new List<String>{'Jan','Feb','March','April','May','June','July','Aug','Sept','Oct','Nov','Dec'};
        
   	public list<Due__c> defaulters{get;set;}
    public list<Due__c> defaulters1{get;set;}
    public list<Society__c> societies;
   
   
   	public Page3_Controller(){
   
       defaulters=new List<Due__c>();
       
       records=new List<selectOption>();
       years=new List<selectOption>();
       months=new List<selectOption>();
       
       societies=[select id, name from Society__c];
        for(Society__c a:societies){
            records.add(new selectoption(a.id,a.name));
        }
        
        for(String y:yearsToAdd){
            years.add(new selectoption(y,y));
        }
        
        for(String m:monthsToAdd){
            months.add(new selectoption(m,m));
        }
        

   	}
    
    public class wrapDues{
        public Due__c due{get;set;}
        public Boolean checked{get;set;}
        public wrapDues(Due__c d){
            due=d;
            checked=true;
        }
    }
    
   public pageReference showRecords(){
       defaulters=[select id, member_name__c, dues_remaining__c,Member_Name__r.Name, Member_Name__r.Email__c, Month__c from Due__c where 
                   society_name__c=:selectedSociety and year__c=:selectedYear and month__c=:selectedMonth and dues_remaining__c>0];
       if(wrapDuesList==null){
           wrapDuesList = new List<wrapDues>();
            for(Due__c a: defaulters) {
                wrapDuesList.add(new wrapDues(a));
            }
        }
       checkedDues=new List<Due__c>();
       for(wrapDues wrapDuesObj:wrapDuesList){
           if(wrapDuesObj.checked == true) {
                checkedDues.add(wrapDuesObj.due);
            }
       }
   		return null;
   }
    
    public PageReference sendReminderEmail(){
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        for(Due__c d:checkedDues){
            if(d.Member_Name__r.Email__c!=null){
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                List<String> sendTo = new List<String>();
      			sendTo.add(d.Member_Name__r.Email__c);
      			mail.setToAddresses(sendTo);
                
                mail.setReplyTo('saie_shendage@persistent.com');
      			mail.setSenderDisplayName('Secretary of the Society');
    			mail.setSubject('Remaining Dues Not Paid');
              String body = 'Dear ' + d.Member_Name__r.Name + ', ';
              body += 'Your remaining dues are '+d.Dues_Remaining__c+' for the month of '+d.Month__c;
              body += ' Please pay the dues Asap, otherwise penalty would be added.';
              mail.setHtmlBody(body);
            
              // Step 5. Add your email to the master list
              mails.add(mail);
            }
        }
        Messaging.sendEmail(mails);
        return null;
    }
    
    public PageReference addDues(){
        defaulters1=[select id, member_name__c,Total_Dues__c, dues_remaining__c,Dues_Paid__c from Due__c where 
                   society_name__c=:selectedSociety and year__c=:selectedYear and month__c=:selectedMonth and dues_remaining__c>0];
      	return null;
    }
    
    public void add(){
        update defaulters1;
    }
    
}
 

Saie, Please let me know it is working or not.

Please mark best answer so that other people would take reference from it.

Thanks
 

 

All Answers

Saie Shendage 7Saie Shendage 7
I have created lookup relationship on Due object for Member and Society objects with Field label Member_Name, Society_Name respectively.
Saie Shendage 7Saie Shendage 7
member_name__c --> gives me id of respective member
Member_Name__r.Name --> gives me actual name of the member (child to parent query)
Malika Pathak 9Malika Pathak 9

Hi Saie,

Please Find The Solution.  How to write test class for below apex controller?

Test Class  with 100% coverage

@isTest
public class Page3_ControllerTest {
    @isTest
    public static void page3(){
        Society__c testSoc=new Society__c();
        testSoc.Name='Some Name';
        testSoc.Reg_Code__c='12345';
        testSoc.Location__c='Some Location';
        testSoc.Formation_Year__c='2012';
        insert testSoc;
        
        member_name__c memberNameObj=new member_name__c();
        memberNameObj.Name='John';
        memberNameObj.Email__c='abc@gmail.com';
        insert memberNameObj;
        
        Due__c dueObj=new Due__c();
        dueObj.Name='check';
        dueObj.year__c=string.valueOf(Date.today().Year());    //'2021' 
        dueObj.month__c=string.valueOf(Date.today().Month());     //'1';
        dueObj.Society_Name__c=testSoc.id;
        dueObj.member_name__c=memberNameObj.Id;
        dueObj.dues_remaining__c=1000;
        insert dueObj;
        
        Due__c dueObj1=new Due__c();
        dueObj1.Name='check1';
        dueObj1.year__c=string.valueOf(Date.today().Year());    //'2021' 
        dueObj1.month__c=string.valueOf(Date.today().Month());     //'1';
        dueObj1.dues_remaining__c=1000;
        dueObj1.Society_Name__c=testSoc.id;
        dueObj1.member_name__c=memberNameObj.Id;
        insert dueObj1;
        
        test.startTest();
        Page3_Controller page3Obj=new Page3_Controller();
        page3Obj.selectedSociety=testSoc.id;
        page3Obj.selectedYear=string.valueOf(Date.today().Year());
        page3Obj.selectedMonth=string.valueOf(Date.today().Month());
        
        page3Obj.showRecords();
        page3Obj.addDues();
        page3Obj.add();
        page3Obj.sendReminderEmail();
        test.stopTest();
        
    }
}

apex class

If you do wrapDues class of checked=true then test coverage is 100%

and if you do checked=false then test coverage is 78%.

public class Page3_Controller {
	public string selectedSociety{get;set;}
    public string selectedYear{get;set;}
    public string selectedMonth{get;set;}
    
    public List<wrapDues> wrapDuesList{get;set;}
    public List<Due__c> checkedDues{get;set;}
    
   	public list<selectOption> records{get;set;}
    public list<selectOption> years{get;set;}
    public list<selectOption> months{get;set;}
    
    public list<String> yearsToAdd=new List<String>{'2015','2016','2017','2018','2019','2020','2021'};
    
    public list<String> monthsToAdd=new List<String>{'Jan','Feb','March','April','May','June','July','Aug','Sept','Oct','Nov','Dec'};
        
   	public list<Due__c> defaulters{get;set;}
    public list<Due__c> defaulters1{get;set;}
    public list<Society__c> societies;
   
   
   	public Page3_Controller(){
   
       defaulters=new List<Due__c>();
       
       records=new List<selectOption>();
       years=new List<selectOption>();
       months=new List<selectOption>();
       
       societies=[select id, name from Society__c];
        for(Society__c a:societies){
            records.add(new selectoption(a.id,a.name));
        }
        
        for(String y:yearsToAdd){
            years.add(new selectoption(y,y));
        }
        
        for(String m:monthsToAdd){
            months.add(new selectoption(m,m));
        }
        

   	}
    
    public class wrapDues{
        public Due__c due{get;set;}
        public Boolean checked{get;set;}
        public wrapDues(Due__c d){
            due=d;
            checked=true;
        }
    }
    
   public pageReference showRecords(){
       defaulters=[select id, member_name__c, dues_remaining__c,Member_Name__r.Name, Member_Name__r.Email__c, Month__c from Due__c where 
                   society_name__c=:selectedSociety and year__c=:selectedYear and month__c=:selectedMonth and dues_remaining__c>0];
       if(wrapDuesList==null){
           wrapDuesList = new List<wrapDues>();
            for(Due__c a: defaulters) {
                wrapDuesList.add(new wrapDues(a));
            }
        }
       checkedDues=new List<Due__c>();
       for(wrapDues wrapDuesObj:wrapDuesList){
           if(wrapDuesObj.checked == true) {
                checkedDues.add(wrapDuesObj.due);
            }
       }
   		return null;
   }
    
    public PageReference sendReminderEmail(){
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        for(Due__c d:checkedDues){
            if(d.Member_Name__r.Email__c!=null){
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                List<String> sendTo = new List<String>();
      			sendTo.add(d.Member_Name__r.Email__c);
      			mail.setToAddresses(sendTo);
                
                mail.setReplyTo('saie_shendage@persistent.com');
      			mail.setSenderDisplayName('Secretary of the Society');
    			mail.setSubject('Remaining Dues Not Paid');
              String body = 'Dear ' + d.Member_Name__r.Name + ', ';
              body += 'Your remaining dues are '+d.Dues_Remaining__c+' for the month of '+d.Month__c;
              body += ' Please pay the dues Asap, otherwise penalty would be added.';
              mail.setHtmlBody(body);
            
              // Step 5. Add your email to the master list
              mails.add(mail);
            }
        }
        Messaging.sendEmail(mails);
        return null;
    }
    
    public PageReference addDues(){
        defaulters1=[select id, member_name__c,Total_Dues__c, dues_remaining__c,Dues_Paid__c from Due__c where 
                   society_name__c=:selectedSociety and year__c=:selectedYear and month__c=:selectedMonth and dues_remaining__c>0];
      	return null;
    }
    
    public void add(){
        update defaulters1;
    }
    
}
 

Saie, Please let me know it is working or not.

Please mark best answer so that other people would take reference from it.

Thanks
 

 

This was selected as the best answer
Saie Shendage 7Saie Shendage 7
Hey Malika! Thank you! But primary key of due object is auto number. So there is no such name field.
Also Month and Year are picklists. So I cannot assign value using string.valueOf(Date.today().Year()) orstring.valueOf(Date.today().Month()).
Dues_remaining__c is a formula field which is calculated as total_dues__c - dues_paid__c, so it is not writable.
I did a little editing to the test class you wrote, but now it's giving me 67% code coverage. Please help out if you can do something.
@isTest
public class Page3_ControllerTest {
    @isTest
    public static void page3(){
        Society__c testSoc=new Society__c();
        testSoc.Name='Some Name';
        testSoc.Reg_Code__c='12345';
        testSoc.Location__c='Some Location';
        testSoc.Formation_Year__c='2012';
        insert testSoc;
        
        member__c memberNameObj=new member__c();
        memberNameObj.Name='John';
        memberNameObj.Email__c='abc@gmail.com';
        insert memberNameObj;
        
        Due__c dueObj=new Due__c();
        dueObj.year__c='2021';    //'2021' 
        dueObj.month__c='January';     //'1';
        dueObj.Society_Name__c=testSoc.id;
        dueObj.member_name__c=memberNameObj.Id;
        dueObj.Total_Dues__c=1000;
        dueObj.dues_paid__c=500;
        insert dueObj;
        
        Due__c dueObj1=new Due__c();
        dueObj1.year__c='2021';    //'2021' 
        dueObj1.month__c='January';     //'1';
        dueObj.Total_Dues__c=1000;
        dueObj.dues_paid__c=500;
        dueObj1.Society_Name__c=testSoc.id;
        dueObj1.member_name__c=memberNameObj.Id;
        insert dueObj1;
        
        test.startTest();
        Page3_Controller page3Obj=new Page3_Controller();
        page3Obj.selectedSociety=testSoc.id;
        page3Obj.selectedYear=string.valueOf(Date.today().Year());
        page3Obj.selectedMonth=string.valueOf(Date.today().Month());
        
        page3Obj.showRecords();
        page3Obj.addDues();
        page3Obj.add();
        page3Obj.sendReminderEmail();
        test.stopTest();
        
    }
}
Saie Shendage 7Saie Shendage 7
I tried checked=true, it is still 67%
Malika Pathak 9Malika Pathak 9

Hi Saie,

try below code 

@isTest
public class Page3_ControllerTest {
    @isTest
    public static void page3(){
        Society__c testSoc=new Society__c();
        testSoc.Name='Some Name';
        testSoc.Reg_Code__c='12345';
        testSoc.Location__c='Some Location';
        testSoc.Formation_Year__c='2012';
        insert testSoc;
        
        Member__c memberNameObj=new Member__c();
        memberNameObj.Name='John';
        memberNameObj.Email__c='abc@gmail.com';
        insert memberNameObj;
        
        
        Due__c dueObj=new Due__c();
        dueObj.Name='check';
        dueObj.year__c=string.valueOf(Date.today().Year());    //'2021' 
        dueObj.month__c=string.valueOf(Date.today().Month());     //'1';
        dueObj.Society_Name__c=testSoc.id;
        dueObj.member_name__c=memberNameObj.Id;
        dueObj.dues_remaining__c=1000;
        insert dueObj;
        
        Due__c dueObj1=new Due__c();
        dueObj1.Name='check1';
        dueObj1.year__c=string.valueOf(Date.today().Year());    //'2021' 
        dueObj1.month__c=string.valueOf(Date.today().Month());     //'1';
        dueObj1.dues_remaining__c=1000;
        dueObj1.Society_Name__c=testSoc.id;
        dueObj1.member_name__c=memberNameObj.Id;
        insert dueObj1;
        
        
        
        test.startTest();
        Page3_Controller page3Obj=new Page3_Controller();
        page3Obj.selectedSociety=testSoc.id;
        page3Obj.selectedYear=string.valueOf(Date.today().Year());
        page3Obj.selectedMonth=string.valueOf(Date.today().Month());
        
        page3Obj.showRecords();
        page3Obj.addDues();
        page3Obj.add();
        page3Obj.sendReminderEmail();
        test.stopTest();
        
    }
}
Saie Shendage 7Saie Shendage 7
Hey Malika can you tell me how to write assertEquals statements in this test class code?
Please help.