+ Start a Discussion
Sylvie SerpletSylvie Serplet 

Apex Test Class for Standard Controller + Extension

Hi All,
These are my Controller and my Test Class.
Whatever I change I could not reach more than 50% coverage.
Could you please help me to get at least 75% to deploy in Production?
public class MyCPDPointsAPEXController {
    
@AuraEnabled    
    public CPD_Points_Total__c total {get;set;}
    string recordId = ApexPages.currentPage().getParameters().get('recordId');
    
    public MyCPDPointsAPEXController(ApexPages.StandardController controller) { 
        
        total = [select Id, Name, Total_Points__c, (select Id, Activity_Date__c, Activity_Title__c, Organiser_Company__c, Points__c from CPD_Register__r) from CPD_Points_Total__c where Id=:ApexPages.currentPage().getParameters().get('recordId')];
    }
    
    public PageReference cancel(){   
        return new PageReference('/' + recordId);   
    }
}
 
@isTest
private class MyCPDPointsAPEXTest {
    
    static testMethod void MyTest()
    {
        CPD_Points_Total__c total = new CPD_Points_Total__c(Name='Test-2017');  
        
        ApexPages.CurrentPage().getparameters().put('id', total.id);      
        
        Apexpages.StandardController sc = new Apexpages.StandardController(total);
        MyCPDPointsAPEXController ext = new MyCPDPointsAPEXController(sc); 
        
        ext.cancel();      
    }
}



Thank you in advance for your help.
Sylvie
 
Best Answer chosen by Sylvie Serplet
Alain CabonAlain Cabon
Hi Sylvie,

You can look at the correct class perhaps (not MyCPDPointsAPEXController but CPDPointsAPEXController)

The code below has been tested:
public class CPDPointsAPEXController {
    
    public CPD_Points_Total__c total {get;set;}
    string recordId = ApexPages.currentPage().getParameters().get('recordId');
    
    public CPDPointsAPEXController(ApexPages.StandardController controller) { 
        
        total = [select Id, Name, Total_Points__c, 
                 (select Id, Activity_Date__c, Activity_Title__c, Organiser_Company__c, Points__c from CPD_Register__r) 
                 from CPD_Points_Total__c where Id=:ApexPages.currentPage().getParameters().get('recordId')];
    }
    
    public PageReference doCancel(){   
        return new PageReference('/' + recordId);   
    }
}
@isTest
public class CPDPointsAPEXCtrlTest {
    
    static testMethod void MyTest()
    {        
        Account myaccount = new Account (name='Test');
        insert myaccount;
        Contact mycontact = new Contact (firstname='Barbie', lastname='Chette');
        insert mycontact;
        CPD_Points_Total__c total = new CPD_Points_Total__c (Name='Test-2017'); 
        insert total;
        CPD_Register__c point = new CPD_Register__c (Total_CPD_Points_Record__c = total.id, 
                                                     Contact__c = mycontact.id,
                                                     Activity_Date__c = date.today(),
                                                     Activity_Title__c = 'test',
                                                     Organiser_Company__c = myaccount.id,
                                                     Points__c = 100
                                                    );   
        insert point;
        PageReference pageRef = Page.MyCPDPointsRegister;
        pageRef.getparameters().put('recordId', total.id);  
        Test.setCurrentPage(pageRef);
        
        Apexpages.StandardController sc = new Apexpages.StandardController(total);
        CPDPointsAPEXController ext = new  CPDPointsAPEXController(sc);         
        ext.doCancel();      
    }
}


User-added image

100% (sure). 

User-added image


A+

All Answers

Jagadeesh111Jagadeesh111
Hi Sylvie, 


you have to replace  below line ApexPages.CurrentPage().getparameters().put('id', total.id);   into 

ApexPages.CurrentPage().getparameters().put('recordId', total.id);

Please check and let me know.

Thanks,
Jagadeesh
Alain CabonAlain Cabon
There is a solution above.
 
You can see clearly the lines of code that aren't covered and indicate them with your questions for the next time (helpful for big classes).

Checking Code Coverage: 

You can view code coverage in several places in the Developer Console.

To view line-by-line code coverage for an Apex class, open the tested class. The Code Coverage menu (at the top left) will include one or more of the following options depending on the tests you have implemented:
  • None
  • All Tests: The percentage of code coverage from all test runs.
  • className.methodName: The percentage of code coverage from a method executed during a test run.
Lines of code that are covered by tests are blue. Lines of code that aren’t covered are red. Lines of code that don’t require coverage (for example, curly brackets, comments, and System.debugcalls) are left white.

https://help.salesforce.com/articleView?id=code_dev_console_tests_coverage.htm&type=0
Varun SinghVarun Singh
Hi SylVie
You have to create child record  CPD_Register__r  for CPD_Points_Total__c .then assign 
1-create CPD_Register__r  cd=new CPD_Register__r ((Name=' child Test-2017');
insert;
2-create CPD_Points_Total__c total = new CPD_Points_Total__c(Name='Test-2017'); 
assign parent id to child records to making  relationship
insert total ;

I hope it is  helpful.
 
Sylvie SerpletSylvie Serplet
Hi all,
Thank you for all your tips. Unfortunatly, when I change id by recordId my code coverage stays a 50%.
When I had the following line to create the child record, no change still no more than 50% coverage.
CPD_Register__c point = new CPD_Register__c(Total_CPD_Points_Record__c = total.id);
Lines that are not covered are 4, 12 and 13.

Any other thought?
Thank you,
Sylvie
Alain CabonAlain Cabon
12-13) public PageReference cancel(){  
       return new PageReference('/' + recordId);  
  }

It is strange to have : @AuraEnabled  and PageReference together but it is possible for the compiler.

The AuraEnabled annotation provides support for Apex methods and properties to be used with the Lightning Component framework.
and PageReference is for Visualforce pages.

Why do you need @AuraEnabled here ?
 
Sylvie SerpletSylvie Serplet
Hi Alain,
My develpment is based on a Lightning Component that display a button to open the VF page in a Community. The Apex controller is for both Lightning Component and VF page. I could add codes for both if needed. Just let me know. Thank you.
Sylvie
Alain CabonAlain Cabon
Ok.  

"get at least 75% to deploy in Production?" 75% is the global average for all your code and therefore, the global number of lines is also important.

You can deploy in production with 5% for one class and 90% for another if the first class is small.

Reliable ways to calculate Overall Code Coverage in salesforce​:
https://help.salesforce.com/articleView?id=000199478&type=1

Setup --> Apex classes --> Calculate Overall Code Coverage

If you have a lot of lines of code, it is not three uncovered lines more or less that could change your global average.

But it is still interesting to know why  ext.cancel();    doesn't work for the lines 12-13 (?)
Sylvie SerpletSylvie Serplet
Hi Alain,

I know that but I am starting a brand new org and want to have a least 75% coverage for all my codes before it become unmanageable....

I do not understand either why ext.cancel(); does not work!
Alain CabonAlain Cabon
That seems an interference with the standard cancel (the direct binding syntax)

<apex:commandButton action=”{!cancel}” value=”Cancel” />   // doesn't need anything in the code (direct binding)
https://developer.salesforce.com/page/Building_Visualforce_Pages_Using_the_Standard_Controller

You should try to rename it "doCancel()":

<apex:commandButton value="Cancel" action="{!doCancel}" immediate="TRUE"/>

// Cancel button
controllerExt.doCancel();

http://www.pawelwozniak.info/index.php/salesforce-com/apex-code-tests/100-vf-controller-test-template
 
Sylvie SerpletSylvie Serplet
Hi Alain,
Thank you for trying to solve this issue. I have made the changes but unfortunatly it does not change anything, still only 50% coverage.
Sylvie
Alain CabonAlain Cabon
Sylvie,

Did yo try without @AuraEnabled because there is no other reason now that controllerExt.doCancel(); doesn't work?

Could you post your current complete classes and I will replicate your problem by just out of curiosity (et je ne veux pas mourir idiot)?

Alain.
Sylvie SerpletSylvie Serplet
Hi Alain,

Same result without @AuraEnabled. Current classes as follow.
public class MyCPDPointsAPEXController {
    
    public CPD_Points_Total__c total {get;set;}
    string recordId = ApexPages.currentPage().getParameters().get('recordId');
    
    public MyCPDPointsAPEXController(ApexPages.StandardController controller) { 
        
        total = [select Id, Name, Total_Points__c, (select Id, Activity_Date__c, Activity_Title__c, Organiser_Company__c, Points__c from CPD_Register__r) from CPD_Points_Total__c where Id=:ApexPages.currentPage().getParameters().get('recordId')];
    }
    
    public PageReference doCancel(){   
        return new PageReference('/' + recordId);   
    }
}
 
@isTest
public class MyCPDPointsAPEXTest {
    
    static testMethod void MyTest()
    {
        CPD_Points_Total__c total = new CPD_Points_Total__c(Name='Test-2017');  
        
        CPD_Register__c point = new CPD_Register__c(Total_CPD_Points_Record__c = total.id, Contact__c='0039000001SNL65');  
         
        
        ApexPages.CurrentPage().getparameters().put('recordId', total.id);      
        
        Apexpages.StandardController sc = new Apexpages.StandardController(total);
        MyCPDPointsAPEXController ext = new MyCPDPointsAPEXController(sc); 
        
        ext.doCancel();      
    }
}

Merci,
Sylvie​
 
Alain CabonAlain Cabon
Contact__c mycontact = new Contact__c(firstname='Barbie', lastname='Chette');
 CPD_Register__c point = new CPD_Register__c(Total_CPD_Points_Record__c = total.id, Contact__c= mycontact.id); 
...
PageReference pageRef = Page.yourVFPage;
pageRef.getparameters().put('recordId', total.id);  // ApexPages.CurrentPage().getparameters().put('recordId', total.id);  
Test.setCurrentPage(pageRef);
...

one moretime (I didn't replicate the code for now, it is too late but tomorrow we will get this 100% I hope)
Alain CabonAlain Cabon

 total = [select Id, Name, Total_Points__c, (select Id, Activity_Date__c, Activity_Title__c, Organiser_Company__c, Points__c from CPD_Register__r)
 from CPD_Points_Total__c 
where Id=:ApexPages.currentPage().getParameters().get('recordId')];

so: 

Account myaccount = new Account(name='Test');
Contact__c mycontact = new Contact__c(firstname='Barbie', lastname='Chette');
CPD_Points_Total__c total = new CPD_Points_Total__c(Name='Test-2017', Total_Points__c = 100); 
CPD_Register__c point = new CPD_Register__c(Total_CPD_Points_Record__c = total.id, 
Contact__c=mycontact.id,
Activity_Date__c = date.today(),
Activity_Title__c = 'test'
Organiser_Company__c = myaccount.id,
Points__c = 100

); 
 
Sylvie SerpletSylvie Serplet
Hi Alain,
I have deleted the 2 classes and recreated them with a new name, in case something went wrong in the connection between them.

My code now is as follow and still 50% coverage.
@isTest
public class CPDPointsAPEXCtrlTest {
    
    static testMethod void MyTest()
    {        
        Account myaccount = new Account (name='Test');
        Contact mycontact = new Contact (firstname='Barbie', lastname='Chette');
        CPD_Points_Total__c total = new CPD_Points_Total__c (Name='Test-2017'); 
        CPD_Register__c point = new CPD_Register__c (Total_CPD_Points_Record__c = total.id, 
                                                    Contact__c = mycontact.id,
                                                    Activity_Date__c = date.today(),
                                                    Activity_Title__c = 'test',
                                                    Organiser_Company__c = myaccount.id,
                                                    Points__c = 100
                                                   );   
        PageReference pageRef = Page.MyCPDPointsRegister;
        pageRef.getparameters().put('recordId', total.id);  
        Test.setCurrentPage(pageRef);
        
        Apexpages.StandardController sc = new Apexpages.StandardController(total);
        CPDPointsAPEXCtrl ext = new CPDPointsAPEXCtrl(sc);         
        ext.doCancel();      
    }
}

And this is the VF page.
<apex:page standardController="CPD_Points_Total__c" extensions="CPDPointsAPEXCtrl" sidebar="false" showHeader="false" >    
    
    <apex:slds />   
    <div class="slds-scope">    
        <apex:form >
            <div class="slds-text-heading_medium slds-text-align_center">  
                <br/>        
                <h1>CPD Points Register - {!total.Name}</h1> 
                <h1 style="font-size:18px;">Total Points: {!total.Total_Points__c}</h1> 
                <br/>
            </div>       
            <apex:pageBlock mode="maindetail">  
                <apex:dataTable value="{!total.CPD_Register__r}" var="point" columnsWidth="15%,35%,35%,15%" styleClass="slds-table slds-table_bordered slds-table_cell-buffer" >
                    <apex:column headervalue="Activity Date" headerClass="slds-text-title_caps" value="{!point.Activity_Date__c}"/>                               
                    <apex:column headervalue="Activity Title" headerClass="slds-text-title_caps" value="{!point.Activity_Title__c}"/>                     
                    <apex:column headervalue="Organiser/Company" headerClass="slds-text-title_caps" value="{!point.Organiser_Company__c}"/>                    
                    <apex:column headervalue="Points" headerClass="slds-text-title_caps" value="{!point.Points__c}"/>                     
                </apex:dataTable> 
            </apex:pageBlock>
            <div class="slds-align_absolute-center">  
                <apex:commandButton value="Print" onclick="window.print();" styleClass="slds-button slds-button_brand"/>    
                <apex:commandButton action="{!doCancel}" value="Cancel" immediate="true" styleClass="slds-button slds-button_neutral"/>
            </div>      
        </apex:form>
    </div>
</apex:page>

Mille merci encore pour ton aide.
Sylvie
Alain CabonAlain Cabon
The "insert" should also exist for the tested class..
 
@isTest
public class CPDPointsAPEXCtrlTest {
    
    static testMethod void MyTest()
    {        
        Account myaccount = new Account (name='Test');
        insert myaccount;
        Contact mycontact = new Contact (firstname='Barbie', lastname='Chette');
        insert mycontact;
        CPD_Points_Total__c total = new CPD_Points_Total__c (Name='Test-2017'); 
        insert total;
        CPD_Register__c point = new CPD_Register__c (Total_CPD_Points_Record__c = total.id, 
                                                    Contact__c = mycontact.id,
                                                    Activity_Date__c = date.today(),
                                                    Activity_Title__c = 'test',
                                                    Organiser_Company__c = myaccount.id,
                                                    Points__c = 100
                                                   );   
        insert point;
        PageReference pageRef = Page.MyCPDPointsRegister;
        pageRef.getparameters().put('recordId', total.id);  
        Test.setCurrentPage(pageRef);
        
        Apexpages.StandardController sc = new Apexpages.StandardController(total);
        CPDPointsAPEXCtrl ext = new CPDPointsAPEXCtrl(sc);         
        ext.doCancel();      
    }
}

one moretime.
Sylvie SerpletSylvie Serplet
Hi Alain,
If I had the insert the code coverage fall to 0%!
 
Alain CabonAlain Cabon
Hi Sylvie,

You can look at the correct class perhaps (not MyCPDPointsAPEXController but CPDPointsAPEXController)

The code below has been tested:
public class CPDPointsAPEXController {
    
    public CPD_Points_Total__c total {get;set;}
    string recordId = ApexPages.currentPage().getParameters().get('recordId');
    
    public CPDPointsAPEXController(ApexPages.StandardController controller) { 
        
        total = [select Id, Name, Total_Points__c, 
                 (select Id, Activity_Date__c, Activity_Title__c, Organiser_Company__c, Points__c from CPD_Register__r) 
                 from CPD_Points_Total__c where Id=:ApexPages.currentPage().getParameters().get('recordId')];
    }
    
    public PageReference doCancel(){   
        return new PageReference('/' + recordId);   
    }
}
@isTest
public class CPDPointsAPEXCtrlTest {
    
    static testMethod void MyTest()
    {        
        Account myaccount = new Account (name='Test');
        insert myaccount;
        Contact mycontact = new Contact (firstname='Barbie', lastname='Chette');
        insert mycontact;
        CPD_Points_Total__c total = new CPD_Points_Total__c (Name='Test-2017'); 
        insert total;
        CPD_Register__c point = new CPD_Register__c (Total_CPD_Points_Record__c = total.id, 
                                                     Contact__c = mycontact.id,
                                                     Activity_Date__c = date.today(),
                                                     Activity_Title__c = 'test',
                                                     Organiser_Company__c = myaccount.id,
                                                     Points__c = 100
                                                    );   
        insert point;
        PageReference pageRef = Page.MyCPDPointsRegister;
        pageRef.getparameters().put('recordId', total.id);  
        Test.setCurrentPage(pageRef);
        
        Apexpages.StandardController sc = new Apexpages.StandardController(total);
        CPDPointsAPEXController ext = new  CPDPointsAPEXController(sc);         
        ext.doCancel();      
    }
}


User-added image

100% (sure). 

User-added image


A+
This was selected as the best answer
Sylvie SerpletSylvie Serplet
Fantastic, thank you so much Alain.
I still had to add some more fields to pass a validation rule and a flow!
Nagaraju Mogili 33Nagaraju Mogili 33
what is the 'MyCPDPointsRegister' here,can you explain me ,  I have the same scenario to work
 
bouscalbouscal
@Nagaraju, MYCPDPointsRegister is the name of the apex page @Sylvie posted