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
MaheemSamMaheemSam 

Code Coverage for Class using visualforce page

Hi,

  We have created new custom object called SPR__c which is related to opportunity in SPR we have created a button which will call the below class from visual force page.  below is the class

Class
public class  check_spr_coterm
{
 
 Integer Olicheck;
 Integer Athcheck;
 String PageID; 
 String P_SPR_Approver_Director;
 String P_SPR_Approver_RVP;
 String P_SPR_Approver_GVP;
 String P_SPR_Approver_EVP;  
 
 public check_spr_coterm()
 {
   SPR__c SP;
   //OpportunityLineItem OLI;
    
   SP = [select id,Opportunity__c from SPR__c 
          where Id = : ApexPages.currentPage().getParameters().get('id') limit 1];
   
   PageID = ApexPages.currentPage().getParameters().get('id');
   
  List<SPR__c> SPRO = new List<SPR__c>();

   SPRO = [select id,SPR_Approver_Director__c,SPR_Approver_RVP__c,SPR_Approver_GVP__c,SPR_Approver_EVP__c from SPR__c 
           where 
           id = :ApexPages.currentPage().getParameters().get('id') and
           ( SPR_Approver_Director__c = null or SPR_Approver_RVP__c = null or 
             SPR_Approver_GVP__c = null or SPR_Approver_EVP__c = null ) limit 1 ];
             
      if(!SPRO.isEmpty()) // check if list is not empty
        {       
       P_SPR_Approver_Director = SPRO[0].SPR_Approver_Director__c;
       P_SPR_Approver_RVP = SPRO[0].SPR_Approver_RVP__c;  
       P_SPR_Approver_GVP = SPRO[0].SPR_Approver_GVP__c;
       P_SPR_Approver_EVP = SPRO[0].SPR_Approver_EVP__c;
        }
      else
      {
        P_SPR_Approver_Director = 's';
        P_SPR_Approver_RVP =  's';  
        P_SPR_Approver_GVP =  's';
        P_SPR_Approver_EVP =  's';
       }     
     
   List<AggregateResult> OLI = [select count(id) olicnt from OpportunityLineItem 
                                where opportunityid = :SP.Opportunity__c and name like '%COTERM%' ];
    
   List<AggregateResult>  ATH = [select count(id) athcnt from  Attachment 
                                 where parentid = :ApexPages.currentPage().getParameters().get('id')];  
 
   Olicheck = (Integer)OLI[0].get('olicnt');
   Athcheck = (Integer)ATH[0].get('athcnt');  
     
 }
 public void pageAction(){
 
     if ( P_SPR_Approver_Director == NULL || P_SPR_Approver_RVP == NULL || P_SPR_Approver_GVP == NULL || P_SPR_Approver_EVP == NULL  )
     {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'Your SPR approvers have not been set up, please contact the SFDC Administrator @ SFDC@fortinet.com'));  
     }
 
     else if( Olicheck > 0 && Athcheck ==0) // COTERM product exist and attached is missing this will fire
     {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'An RTS Quote is required for the COTERM product.Please attach quote(s) and then resubmit your SPR for approval'));     
     }
     
     else if ( P_SPR_Approver_Director <> NULL && P_SPR_Approver_RVP <> NULL && P_SPR_Approver_GVP <> NULL && P_SPR_Approver_EVP <> NULL  )
     {
       Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
       req.setObjectId(PageID);
       Approval.ProcessResult result = Approval.process(req);
       ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'Sucessfully submitted for approval'));
       redirectpage();
      }
     
 }
 
 
 public PageReference redirectpage()
 {
   PageReference pageRef = new PageReference('/' + PageID);
   pageRef.setRedirect(true);
   return pageRef;
 }
 
 
}

Visual force Page.
<apex:page controller="check_spr_coterm" action="{!pageAction}">
<apex:pageMessages />
<apex:form >
        <apex:commandButton value="Ok" action="{!redirectpage}" oncomplete="abc();"/>
    </apex:form>
<script>
function abc() {
    window.location = 'https://www.google.com';
}
</script>
</apex:page>

<!--
<apex:page controller="check_spr_coterm">
<script>
window.alert('{!$CurrentPage.Parameters.Id}');
window.parent.opener.location.reload(true);
window.parent.close();
</script>
</apex:page>
-->

Wrote below Test Class which is still showing 0% code coverage Please suggest me how to add code coverage test class for above class 
@isTest(seealldata=true)
public class  test_check_spr_coterm
{
   static testMethod void test_check_spr_coterm(){
   
  Account Act = new Account( Name = 'Test Sudhir Ac',Website='www.sudhir.com',Industry='Legal',BillingStreet='894', BillingCity='sunnyvalley', BillingState='CA', 
                             BillingPostalCode='997',BillingCountry='USA');  

  insert Act; 
   
  Opportunity Opp = new Opportunity(Name = 'Test Class Sudhir',AccountId=Act.id,Closedate=system.today(),StageName='Omit from Forecast',Deal_Type__c='Refresh' );  

  insert Opp;  
   
   
   SPR__c SPR = new  SPR__c(Opportunity__c=opp.id,Partner_Account__c='0018000000pwEyq',Distributor__c='a0N8000000Aiif0',Reason_Needed__c='Budget Constraints',
                            SPR_Approver_Director__c = null,SPR_Approver_RVP__c=null,
                            SPR_Approver_GVP__c=null,SPR_Approver_EVP__c=null  ); 
   
   insert SPR;
     
   //String SPR1 = SPR[0].id;
  
  
 // if([select count() from ProcessInstance where targetobjectid=:SPR1.id] < 1)
     //   {       
            Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
            req.setComments('Approve.');
            req.setNextApproverIds(new Id[] {UserInfo.getUserId()});
            req.setObjectId(SPR.Id);

            //Submit the approval request
            Approval.ProcessResult result = Approval.process(req);

     //   } 
        
   }     

}


Please suggest me how to modify the test class to get code coverage.

Thanks
Sudhir
Best Answer chosen by MaheemSam
Veenesh VikramVeenesh Vikram
Yes , Ideally this method should be called automatically from the "pageAction" method. Still if its not getting covered, we may make a call explicitly:
Test.StartTest();
		 PageReference pageRef = Page.YOURPAGENAME;
		 Test.setCurrentPage(pageRef);				//Set Page
		 // Add parameters to page URL
		 ApexPages.currentPage().getParameters().put('id', SPR.Id);
		check_spr_coterm ctrlr = new check_spr_coterm();
		//Calling Page Action Method
		ctrlr.pageAction();
		ctrlr.redirectpage();
	 Test.StopTest();

 

All Answers

Veenesh VikramVeenesh Vikram
You need to initialize the Class and call its methods from the test cass as well.

Like this:
@isTest(seealldata=true)
public class  test_check_spr_coterm
{
   static testMethod void test_check_spr_coterm(){
   
  Account Act = new Account( Name = 'Test Sudhir Ac',Website='www.sudhir.com',Industry='Legal',BillingStreet='894', BillingCity='sunnyvalley', BillingState='CA', 
                             BillingPostalCode='997',BillingCountry='USA');  

  insert Act; 
   
  Opportunity Opp = new Opportunity(Name = 'Test Class Sudhir',AccountId=Act.id,Closedate=system.today(),StageName='Omit from Forecast',Deal_Type__c='Refresh' );  

  insert Opp;  
   
   
   SPR__c SPR = new  SPR__c(Opportunity__c=opp.id,Partner_Account__c='0018000000pwEyq',Distributor__c='a0N8000000Aiif0',Reason_Needed__c='Budget Constraints',
                            SPR_Approver_Director__c = null,SPR_Approver_RVP__c=null,
                            SPR_Approver_GVP__c=null,SPR_Approver_EVP__c=null  ); 
   
   insert SPR;
     
   //String SPR1 = SPR[0].id;
  
  
 // if([select count() from ProcessInstance where targetobjectid=:SPR1.id] < 1)
     //   {       
            Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
            req.setComments('Approve.');
            req.setNextApproverIds(new Id[] {UserInfo.getUserId()});
            req.setObjectId(SPR.Id);

            //Submit the approval request
            Approval.ProcessResult result = Approval.process(req);

     //   } 
	 
	 Test.StartTest();
		check_spr_coterm ctrlr = new check_spr_coterm();
	 Test.StopTest();
        
   }     

}

This may get you the coverage.

Best Regards
Veenesh
MaheemSamMaheemSam
Thanks Veenesh for you reply since I am not passing any value to class check_spr_coterm I am getting below error please suggest me how to fix this issue.  below is the error message. 


Class.check_spr_coterm.<init>: line 17, column 1
Class.test_check_spr_coterm.test_check_spr_coterm: line 38, column 1

Thanks
Sudhir
Veenesh VikramVeenesh Vikram
Here the issue is that there is no ID being passed to the VF page,

In the test class, you need to set the page as well as pass an Id to it. Like:
@isTest(seealldata=true)
public class  test_check_spr_coterm
{
   static testMethod void test_check_spr_coterm(){
   
  Account Act = new Account( Name = 'Test Sudhir Ac',Website='www.sudhir.com',Industry='Legal',BillingStreet='894', BillingCity='sunnyvalley', BillingState='CA', 
                             BillingPostalCode='997',BillingCountry='USA');  

  insert Act; 
   
  Opportunity Opp = new Opportunity(Name = 'Test Class Sudhir',AccountId=Act.id,Closedate=system.today(),StageName='Omit from Forecast',Deal_Type__c='Refresh' );  

  insert Opp;  
   
   
   SPR__c SPR = new  SPR__c(Opportunity__c=opp.id,Partner_Account__c='0018000000pwEyq',Distributor__c='a0N8000000Aiif0',Reason_Needed__c='Budget Constraints',
                            SPR_Approver_Director__c = null,SPR_Approver_RVP__c=null,
                            SPR_Approver_GVP__c=null,SPR_Approver_EVP__c=null  ); 
   
   insert SPR;
     
   //String SPR1 = SPR[0].id;
  
  
 // if([select count() from ProcessInstance where targetobjectid=:SPR1.id] < 1)
     //   {       
            Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
            req.setComments('Approve.');
            req.setNextApproverIds(new Id[] {UserInfo.getUserId()});
            req.setObjectId(SPR.Id);

            //Submit the approval request
            Approval.ProcessResult result = Approval.process(req);

     //   } 
	 
	 Test.StartTest();
		 PageReference pageRef = Page.YOURPAGENAME;
		 Test.setCurrentPage(pageRef);				//Set Page
		 // Add parameters to page URL
		 ApexPages.currentPage().getParameters().put('id', SPR.Id);
		check_spr_coterm ctrlr = new check_spr_coterm();
	 Test.StopTest();
        
   }     

}

Thanks
MaheemSamMaheemSam
Thank You Very Much Veenesh you really helped me to get this done. I have 50% code coverage in the class now test class passed sucessfully without any error 

 
Veenesh VikramVeenesh Vikram
Now you just need to create data as per your custom logic and you will get the required coverage.

Kindly Mark the solution solved if it helps.

Veenesh
MaheemSamMaheemSam
public class  check_spr_coterm
{
 
 Integer Olicheck;
 Integer Athcheck;
 String PageID; 
 String P_SPR_Approver_Director;
 String P_SPR_Approver_RVP;
 String P_SPR_Approver_GVP;
 String P_SPR_Approver_EVP;  
 
 public check_spr_coterm()
 {
   SPR__c SP;
   //OpportunityLineItem OLI;
    
   SP = [select id,Opportunity__c from SPR__c 
          where Id = : ApexPages.currentPage().getParameters().get('id') limit 1];
   
   PageID = ApexPages.currentPage().getParameters().get('id');
   
  List<SPR__c> SPRO = new List<SPR__c>();

   SPRO = [select id,SPR_Approver_Director__c,SPR_Approver_RVP__c,SPR_Approver_GVP__c,SPR_Approver_EVP__c from SPR__c 
           where 
           id = :ApexPages.currentPage().getParameters().get('id') and
           ( SPR_Approver_Director__c = null or SPR_Approver_RVP__c = null or 
             SPR_Approver_GVP__c = null or SPR_Approver_EVP__c = null ) limit 1 ];
             
      if(!SPRO.isEmpty()) // check if list is not empty
        {       
       P_SPR_Approver_Director = SPRO[0].SPR_Approver_Director__c;
       P_SPR_Approver_RVP = SPRO[0].SPR_Approver_RVP__c;  
       P_SPR_Approver_GVP = SPRO[0].SPR_Approver_GVP__c;
       P_SPR_Approver_EVP = SPRO[0].SPR_Approver_EVP__c;
        }
      else
      {
        P_SPR_Approver_Director = 's';
        P_SPR_Approver_RVP =  's';  
        P_SPR_Approver_GVP =  's';
        P_SPR_Approver_EVP =  's';
       }     
     
   List<AggregateResult> OLI = [select count(id) olicnt from OpportunityLineItem 
                                where opportunityid = :SP.Opportunity__c and name like '%COTERM%' ];
    
   List<AggregateResult>  ATH = [select count(id) athcnt from  Attachment 
                                 where parentid = :ApexPages.currentPage().getParameters().get('id')];  
 
   Olicheck = (Integer)OLI[0].get('olicnt');
   Athcheck = (Integer)ATH[0].get('athcnt');  
     
 }
 public void pageAction(){
 
     if ( P_SPR_Approver_Director == NULL || P_SPR_Approver_RVP == NULL || P_SPR_Approver_GVP == NULL || P_SPR_Approver_EVP == NULL  )
     {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'Your SPR approvers have not been set up, please contact the SFDC Administrator @ SFDC@fortinet.com'));  
     }
 
     else if( Olicheck > 0 && Athcheck ==0) // COTERM product exist and attached is missing this will fire
     {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'An RTS Quote is required for the COTERM product.Please attach quote(s) and then resubmit your SPR for approval'));     
     }
     
     else if ( P_SPR_Approver_Director <> NULL && P_SPR_Approver_RVP <> NULL && P_SPR_Approver_GVP <> NULL && P_SPR_Approver_EVP <> NULL  )
     {
       Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
       req.setObjectId(PageID);
       Approval.ProcessResult result = Approval.process(req);
       ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'Sucessfully submitted for approval'));
       redirectpage();
      }
     
 }
 
 
 public PageReference redirectpage()
 {
   PageReference pageRef = new PageReference('/' + PageID);
   pageRef.setRedirect(true);
   return pageRef;
 }
 
 
}
Highlighted lines are not comming as covered please advice me to change 
MaheemSamMaheemSam
I will surely make this as answered line betwen 55 to 84 is showing as not covered any suggestion to change this logic
Veenesh VikramVeenesh Vikram
You need to call this method as well in the test class:
@isTest(seealldata=true)
public class  test_check_spr_coterm
{
   static testMethod void test_check_spr_coterm(){
   
  Account Act = new Account( Name = 'Test Sudhir Ac',Website='www.sudhir.com',Industry='Legal',BillingStreet='894', BillingCity='sunnyvalley', BillingState='CA', 
                             BillingPostalCode='997',BillingCountry='USA');  

  insert Act; 
   
  Opportunity Opp = new Opportunity(Name = 'Test Class Sudhir',AccountId=Act.id,Closedate=system.today(),StageName='Omit from Forecast',Deal_Type__c='Refresh' );  

  insert Opp;  
   
   
   SPR__c SPR = new  SPR__c(Opportunity__c=opp.id,Partner_Account__c='0018000000pwEyq',Distributor__c='a0N8000000Aiif0',Reason_Needed__c='Budget Constraints',
                            SPR_Approver_Director__c = null,SPR_Approver_RVP__c=null,
                            SPR_Approver_GVP__c=null,SPR_Approver_EVP__c=null  ); 
   
   insert SPR;
     
   //String SPR1 = SPR[0].id;
  
  
 // if([select count() from ProcessInstance where targetobjectid=:SPR1.id] < 1)
     //   {       
            Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
            req.setComments('Approve.');
            req.setNextApproverIds(new Id[] {UserInfo.getUserId()});
            req.setObjectId(SPR.Id);

            //Submit the approval request
            Approval.ProcessResult result = Approval.process(req);

     //   } 
	 
	 Test.StartTest();
		 PageReference pageRef = Page.YOURPAGENAME;
		 Test.setCurrentPage(pageRef);				//Set Page
		 // Add parameters to page URL
		 ApexPages.currentPage().getParameters().put('id', SPR.Id);
		check_spr_coterm ctrlr = new check_spr_coterm();
		//Calling Page Action Method
		ctrlr.pageAction();
	 Test.StopTest();
        
   }     

}

 
MaheemSamMaheemSam
Thank You Very Much Veenesh my last question below code is not getting covered do we have to call this method also please suggest how to call. 

 
public PageReference redirectpage()
 {
   PageReference pageRef = new PageReference('/' + PageID);
   pageRef.setRedirect(true);
   return pageRef;
 }

Thanks
Sudhir
Veenesh VikramVeenesh Vikram
Yes , Ideally this method should be called automatically from the "pageAction" method. Still if its not getting covered, we may make a call explicitly:
Test.StartTest();
		 PageReference pageRef = Page.YOURPAGENAME;
		 Test.setCurrentPage(pageRef);				//Set Page
		 // Add parameters to page URL
		 ApexPages.currentPage().getParameters().put('id', SPR.Id);
		check_spr_coterm ctrlr = new check_spr_coterm();
		//Calling Page Action Method
		ctrlr.pageAction();
		ctrlr.redirectpage();
	 Test.StopTest();

 
This was selected as the best answer
MaheemSamMaheemSam
Wonderful Veenesh you soloved my issue thank you very much for your help.