+ Start a Discussion
KRISHNAMURTHY KOLUMAM ANANTHARAMAKKRISHNAMURTHY KOLUMAM ANANTHARAMAK 

How do I write a test class for my code to achieve 75% code coverage ?

Hi All,

This is my trigger which will send an email with attachement whenever a pdf is uplaoded in Notes and Attachement. I wrote a test class but it doesn't cover the code? Would be great if anyone could help me on this. Thanks.
 
trigger EmailTrigger on ContentVersion (after insert){
    
    if(Trigger.isAfter){
        
        List<Messaging.SingleEmailMessage> allMessages = new List<Messaging.SingleEmailMessage>(); 
        if(Trigger.isInsert){
        
		    //Retrieve all invoices based on the requried Invoice Ids. Add your criteria to fetch 
		    // relevant invoices in the Where clause based on the Invoice and ContentVersion 
		    // object relationship. Replace <yourInvoiceIdSet> below with the actual Id Set
            List<Invoice_Payment__c> invoiceList = [Select Id, Name
										    From Invoice_Payment__c 
										   where Id IN (SELECT FirstPublishLocationId FROM ContentVersion WHERE Id IN :trigger.new)];
		
            for(ContentVersion cv : trigger.new){

                Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment(); 
                attachment.setBody(Blob.valueof(cv.ContentBodyId));
                attachment.setFileName(cv.Title + '.' + cv.FileType); 
                
                Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage(); 
                
					message.setToAddresses(new String[] { 'andre.nobre@cleantechsolar.com' ,'rupesh.baker@cleantechsolar.com'});
                    message.setccAddresses(new String[] { 'krishnamurthy.ka@cleantechsolar.com' ,'divina.minoza@cleantechsolar.com'});
                
				//Subject with the retrieved Invoice Number
				message.subject = 
					String.format('Your Invoice having Invoice # {0} is due for payment', 
						new String[]{invoiceList[0].Name}); 
                
				//Email body containing Name with the retrieved invoice
				message.plainTextBody = 
					String.format('Your invoice for {0} with the file name {1} is attached alongwith.', 
						new String[]{invoiceList[0].Name, cv.Title});
						
                message.setFileAttachments(new Messaging.EmailFileAttachment[] {attachment}); 
                allMessages.add(message); 
            } 
        }
        Messaging.sendEmail(allMessages); 
    }
}

Kind Regards
Krishnamurthy
Ginny MahantGinny Mahant
Hi Krishnamurthy,
 
    You need to separate the code to send email from your trigger to a util class. Please see code below. Hope this helps.


/**util class to send email**/

public class MailerUtil
{
    public static void sendMailMessage(List <ContentVersion> conVer) 
    {
        List<Messaging.SingleEmailMessage> allMessages = new List<Messaging.SingleEmailMessage>(); 
        
            List<Invoice_Payment__c> invoiceList = [Select Id, Name
                                            From Invoice_Payment__c 
                                           where Id IN (SELECT FirstPublishLocationId FROM ContentVersion WHERE Id IN :conVer)];
        
            for(ContentVersion cv : conVer)
            {

                Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment(); 
                attachment.setBody(Blob.valueof(cv.ContentBodyId));
                attachment.setFileName(cv.Title + '.' + cv.FileType); 
                
                Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage(); 
                
                message.setToAddresses(new String[] { 'andre.nobre@cleantechsolar.com' ,'rupesh.baker@cleantechsolar.com'});
                message.setccAddresses(new String[] { 'krishnamurthy.ka@cleantechsolar.com' ,'divina.minoza@cleantechsolar.com'});
                
                //Subject with the retrieved Invoice Number
                message.subject = 
                String.format('Your Invoice having Invoice # {0} is due for payment', 
                        new String[]{invoiceList[0].Name}); 
                
                //Email body containing Name with the retrieved invoice
                message.plainTextBody = 
                String.format('Your invoice for {0} with the file name {1} is attached alongwith.', 
                new String[]{invoiceList[0].Name, cv.Title});
                        
                message.setFileAttachments(new Messaging.EmailFileAttachment[] {attachment}); 
                allMessages.add(message); 
            } 
        
        Messaging.sendEmail(allMessages); 
    }
   
}



/**trigger**/
trigger EmailTrigger on ContentVersion (after insert){
if(Trigger.isAfter && Trigger.isInsert){
    MailerUtil.sendMailMessage(trigger.new);
}
}

/**test class**/
@istest
public class MailerUtilTest {
    public static testmethod void testvalidate(){
        //insert invoice payment record
        //insert a record of ContentVersion object -- this will fire the trigger and the code to send email 
        //will be executed
    }
}    
}

Regards,
KRISHNAMURTHY KOLUMAM ANANTHARAMAKKRISHNAMURTHY KOLUMAM ANANTHARAMAK
Hi Ginny,

Could you please help me with the test class ?

Thanks
Krishnamurthy
Ginny MahantGinny Mahant
@istest
public class MailerUtilTest {
    public static testmethod void testvalidate(){

 Invoice_Payment__c invpymtRec = new Invoice_Payment__c ();
 //populate data into the record
 //invpymtRec.Amount__c = 1000;
 insert invpymtRec ;

 ContentVersion testContentInsert = new ContentVersion(); 
 testContentInsert.ContentURL='<a target="_blank" href="http://www.google.com/';" rel="nofollow">http://www.google.com/';</a> 
 testContentInsert.Title ='Google.com'; 
 testContentInsert.FirstPublishLocationId = invpymtRec .Id;
 insert testContentInsert; 
//after above insert stmt your triggr will fire and send email; you should get coverage;do let me know how it goes 
   }
KRISHNAMURTHY KOLUMAM ANANTHARAMAKKRISHNAMURTHY KOLUMAM ANANTHARAMAK
Hi Ginny,

When I try to populate the record , for example something like this below:

  invpymtRec.Amount_Payable__c = 5000;

It says that the field is not writeable ?

Please advice.

Thanks.
Ginny MahantGinny Mahant
The field I mentioned was just meant to be taken as an example since I dont know your object and its fields as its a custom object. Please create a record of Invoice_Payment__c  object with the required or mandatory fields populated. If you want further assisstance you can skype me @ ginnymahant.
Ginny MahantGinny Mahant
        Please write the following test class ---

@isTest
public class contentVersionTriggerTest {
 public static testmethod void testvalidate(){  
      ContentVersion content=new ContentVersion(); 
            content.Title='Header_Picture1'; 
            content.PathOnClient='/' + content.Title + '.jpg'; 
            Blob bodyBlobvar=Blob.valueOf('Unit Test ContentVersion Body'); 
            content.VersionData=bodyBlobvar; 
            //content.LinkedEntityId=sub.id;
            content.origin = 'H';
        insert content;
 }
}

In your trigger please put a statement if(!Test.isRunningTest()) before codeline 11 i.e.
List<Invoice_Payment__c> invoiceList = [Select Id, Name
                                            From Invoice_Payment__c
                                           where Id IN (SELECT FirstPublishLocationId FROMContentVersion WHERE Id IN :trigger.new)];
Also, change code from line no. 27 to 34 to 

if(!Test.isRunningTest())
     message.subject = String.format('Your Invoice having Invoice # {0} is due for payment', new String[]{invoiceList[0].Name});
else 
     message.subject = 'Test class message';

//Email body containing Name with the retrieved invoice
if(!Test.isRunningTest())
    message.plainTextBody = String.format('Your invoice for {0} with the file name {1} is attached alongwith.', new String[]{invoiceList[0].Name, cv.Title});
else
    message.plainTextBody = 'Test class message';

//This should give you more than 75% coverage
Ginny MahantGinny Mahant
Hi Kris,

     Hope the issue with Milestone package is resolved. If the suggestion resolved your issue, kindly mark it best answer so as to make it available to others as a proper solution.

Regards,