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
b.gonzalezb.gonzalez 

How do I increase the code coverage for the Apex Class and Apex Trigger?

I created the following Apex Class and Apex Trigger. However the code coverage for the Apex Class is only 63% and the Aoex Trigger is 0%.

How do I increase the code coverage for the Apex Class and Apex Trigger?

Apex Class: ApprovedSFDCRequestPDF
Code Coverage: 63% (13/19)
public class ApprovedSFDCRequestPDF
{
    public SFDC__c SFDCReq;
    //public DateTime craDateTime = DateTime.now();
    private ApexPages.StandardController stdController;
    
    public ApprovedSFDCRequestPDF(ApexPages.StandardController stdController)
    {
        this.stdController = stdController;
        SFDCReq = (SFDC__c)stdController.getRecord();
    } 
    // Attach Approved SFDC Request to current SFDC__c 
    
    public PageReference attach()
    {
        DateTime craDateTime = DateTime.now();
        SFDC__c  f=[select id,name,Submitted_for_Approval__c,SFDC_Request_Status__c from SFDC__c where id=:SFDCReq.id];
        if(f.Submitted_for_Approval__c==True&&f.SFDC_Request_Status__c=='Approved')
        {
            // Get the page definition 
            //PageReference pdfPage = Page.ApprovedSFDCRequestPDF;   
            
            PageReference pdfPage = new PageReference('/apex/ApprovedSFDCRequestPDF?id=' + SFDCReq.id);
           
            
            //pdfPage.getParameters().put('id',SFDCReq.id);
             Blob pdfBlob = null;
            // Generate the pdf blob
            if(!Test.isRunningTest())//added by Najma for #00055992
             pdfBlob = pdfPage.getContent();
            else
            pdfBlob = Blob.valueOf('Test');
            //SFDC__c f=[select id,name from SFDC__c where id=:SFDCReq.id];
            // Create the attachment against the Approved SFDC Request page 
            Attachment a = new Attachment(parentId = f.id, name=f.name + ' - SFDC ' + craDateTime.formatlong() + '.pdf', body = pdfBlob);
            // Insert the attachment into the SFDC Request
            
            insert a;
        }
        PageReference p=new PageReference('/'+f.id);
        p.setredirect(true);
        return p;  
    }
}

Apex Trigger:  CreateSFDCRequestTrigger
Code Coverage: 0% (0/3)
trigger CreateSFDCRequestTrigger on SFDC__c (before update) {
     for(SFDC__c  sfdc : trigger.new){
        if(sfdc.FromApprovalProcess__c == true ){
             GenerateCDRPDF.generateCDRPDFAttachment(sfdc.id, 'sfdc', UserInfo.getSessionId());
        }
    }
}

Thanks!

Beth
Best Answer chosen by b.gonzalez
Stephan SpiegelStephan Spiegel
In your test setup, you'll want to set Submitted_for_Approval__c==True and  SFDC_Request_Status__c=='Approved' on req, so that your test code can exercise that if statement.

Your trigger only fires on update, but your test code doesn't update any SFDC__c objects. You could add this right after Test.startTest() :
req.Subject__c = 'test2';
update req;
That should give you coverage on the trigger.

All Answers

Stephan SpiegelStephan Spiegel
Code coverage comes from test methods. You didn't post any test methods, so it's impossible to know where the 63% coverage comes from, or how to increase it.

In general, you'll want to write test code that updates a SSFDC__c object (to get coverage for the trigger), and test code that constructs the ApprovedSFDCRequestPDF controller and calls the attach() method on the controller. If you create the SFDC__c objects for the test so that the code exercises both branches of your inner if-statement, you should easily get to 100% coverage.
b.gonzalezb.gonzalez
Hi Stephan,

Thank you for your response. I am not sure where I went wrong but here is the test code that I wrote:

/**
 *Last Modified by Najma Ateeq - 00055992
 */
@isTest
private class Test_ApprovedSFDCRequestPDF {
static testMethod void myUnitTest() {
        Account a = new Account();
        String myDate = Datetime.now().format('hhmmssSSS');
        a.Name = 'San Diego Test Company ' + myDate + ' - San Diego ' + myDate;
        a.Site_City__c = 'San Diego ' + myDate;
        a.Site_Street__c = myDate + ' Fake St';
        a.Site_Country__c = 'USA';
        a.PMI_Active_Master__c = true;
        insert a;
        contact c = new Contact();
        c.FirstName = 'Test';
        c.LastName = 'Contact';
        c.AccountId = a.Id;
        c.email = 'test@gmail.com';
    SFDC__c req = new SFDC__c();
        req.SFDC_Request_Name__c = 'test';
        req.Request_Type__c = 'Admin Request';
        req.Priority__c = 'Low';
        req.Severity__c = 'Minor Impact';
        req.Subject__c = 'test';
        insert req;
        Test.startTest();
        ApprovedSFDCRequestPDF extn = new ApprovedSFDCRequestPDF(new ApexPages.StandardController(req));
        extn.attach();
        Test.stopTest();
        system.assertNotEquals(extn,null);
    }
}


Stephan SpiegelStephan Spiegel
In your test setup, you'll want to set Submitted_for_Approval__c==True and  SFDC_Request_Status__c=='Approved' on req, so that your test code can exercise that if statement.

Your trigger only fires on update, but your test code doesn't update any SFDC__c objects. You could add this right after Test.startTest() :
req.Subject__c = 'test2';
update req;
That should give you coverage on the trigger.
This was selected as the best answer
b.gonzalezb.gonzalez
Thank you Stephan!

Beth
Michaela ChrysostomouMichaela Chrysostomou
Hi,
See below my controller and my test class. I am receive 71% code covarage. How can I increase this to 75%??? Any ideas??
---------------------------------------
public class TestingFlag{    

public Testimonies__c objt {get; set;}    

public String currentRecordId {get; set;}         

 public TestingFlag(ApexPages.StandardController controller){    

        currentRecordId =  ApexPages.CurrentPage().getparameters().get('id');            objt = [Select Id, Name, Gender__c, Approved_Story__c,Country_v__c,Contact_Country__c, Age__c,Approved_Name__c, Flag__c From Testimonies__c Where Id = :currentRecordId ];     }          

public Testimonies__c getcurrentRecord(){       
      return objt;         }         

}


---------------------------------------
@Test Class


@isTest private class EmployeeControllerTestClass2 {
PageReference pageRef = Page.TestingFlag;             

 static testMethod void myUnitTest()      {        Testimonies__c obj= new Testimonies__c(English_Translation__c='saf',Audience_Identifier__c='Pars',Country_v__c= 'Cyprus',Status__c='Decide');         insert obj;     

PageReference pageRef = Page.TestingFlag;    
 Test.setCurrentPage(pageRef);    
 pageRef.getParameters().put('Id', String.valueOf(obj.Id));     
 ApexPages.StandardController sc = new ApexPages.StandardController(obj);     
 TestingFlag testAccPlan = new TestingFlag(sc);     
 testAccPlan.currentRecordId= obj.Id;          

}               
}
 
Anshul BagdiyaAnshul Bagdiya
Hi guys, I am trying to increase the code coverage for the following code. Currently, its at 74%. Please help:

Public class AutoConvertLeads
{
    @InvocableMethod
    public static void LeadAssign(List<Id> LeadIds)
    {
            Database.LeadConvert Leadconvert = new Database.LeadConvert();
            Leadconvert.setLeadId(LeadIds[0]);
            LeadStatus Leads= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
            Leadconvert.setConvertedStatus(Leads.MasterLabel);
            Leadconvert.setDoNotCreateOpportunity(TRUE); //Remove this line if you want to   create an opportunity from Lead Conversion 
            Database.LeadConvertResult Leadconverts = Database.convertLead(Leadconvert);
            System.assert(Leadconverts.isSuccess());
   }
}