+ Start a Discussion
Maharajan CMaharajan C 

Test Class to Code Coverage

Hi All,

Can any one Please help to write a test class to my Trigger


trigger sendNotificationTrigger on CampaignMember (after insert) {
    Set<Id> LeadIds = new Set<ID>();
    Test_Setting__c tm;//Assinging Custom setting To the variable tm
    tm=Test_Setting__c.getorgdefaults();
    String Template=tm.Template__c;
    Decimal Days=tm.Threshold_Days__c;
     
    
    for(CampaignMember campMem : Trigger.new){//
        if(campMem.leadid != null){
            LeadIds.add(campMem.leadid);
         
            }
            
    List<Messaging.SingleEmailMessage> mails =new List<Messaging.SingleEmailMessage>();   
    for(Lead ld : [select id, Lead_age__c, Status, owner.email from Lead where id IN : LeadIds])
    if(ld.Status!='Qualified'&&ld.Lead_Age_In_days__c>=Days)
    //Checking Condition Status not equal to Qualified and Lead_Age_In_days__c greater than equal to 30
    {
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();// For Email
                             
      List<String> sendTo = new List<String>();
      sendTo.add(ld.Owner.Email);//sending message via Email to the Owner of the lead
      mail.setToAddresses(sendTo);
      mail.saveAsActivity = false;
      mail.setTemplateId(Template);//Using custom setting field template as template id
       mail.setTargetObjectId(ld.Ownerid);                           
      mails.add(mail);
  Messaging.sendEmail(mails);
}
}
}

Thanks
​Raj.
Best Answer chosen by Maharajan C
nagachandra knnagachandra kn
Hi Maharaja,

Please add this code after the trigger.new for loop in your TRIGGER and try to execute the test class once.

if(test.isRunningTest()){
        
        Days = 0;
    }

Thanks
-Nag
 

All Answers

AshlekhAshlekh
Hi,

Can you please provide what you have written so fas in test class for this code.

And for this class you just need to create a data in test class.

-Thanks
Ashlekh Gera
Maharajan CMaharajan C
Hi Asheikh,

Thanks For your Reply...
Here is the my test Class it Covers the 55% test Code Coverage 

@isTest(SeeAllData = true)
public class sendNotificationTrigger{
    static testMethod void sendNotificationTrigger (){
 
        Test.startTest();
               //Creates Contact to be linked to Campaign Member
       
        
        Campaign cp =  [SELECT Id FROM Campaign LIMIT 1];
        

        Lead t1 = new Lead(Company= 'TestContactF', LastName= 'TestContactL', Email = 'none@navinet.net',Status = 'Open' );
        
                       
                insert t1;
                CampaignMember newMember = 
        new CampaignMember(LeadId = t1.id, status='Sent', campaignid = cp.id);
        insert newMember;
               
              system.assertequals(t1.status,'Open')  ;  
               

        Test.stopTest();

    
}
}

Thanks
Raj
 
nagachandra knnagachandra kn
Try this::
 
@isTest(SeeAllData = false)
public class sendNotificationTrigger{
    static testMethod void sendNotificationTrigger (){
 
        Test.startTest();
               //Creates Contact to be linked to Campaign Member
       
        
      Campaign ca1 = new Campaign(
            Name = 'Testcampaign',
            IsActive = TRUE);

        insert ca1 ;

        Lead lead=new Lead(LastName='test',FirstName='test1',Company='Test',Status='Inquiry');
		lead.Lead_Age_In_days__c = // Please set this value is greater than "Days" value.
		insert lead;  
        
                       
                
                CampaignMember newMember = 
        new CampaignMember(LeadId = lead.id, status='Sent', campaignid = ca1.id);
        insert newMember;
               
              system.assertequals(Lead.status,'Open')  ;  
               

        Test.stopTest();

    
}
}

Dont forget to set  the
Lead_Age_In_days__c value to greater than your custom setting.
Maharajan CMaharajan C
Hi Nagachandra,

Lead_Age_In_Days__c is not writable Field its a Custom Formula Field in the Lead Object
So i got an Error as Lead_Age_In_Days__c  Field is not a writable During save the program

Thanks For you Reply...
Let me Know is there any other possible ways
and also i need to Check the Email Messaging in the Same Test Class
Can You Please Help me Any One...

Thanks
Raj
nagachandra knnagachandra kn
HI Maharaja,

what is the formula ?. you have to set the value otherwise the if block cant be covered. let me know the formula. i will help you out.
Maharajan CMaharajan C
Hi Naga,

Its Formula(Number) Field which is used to calculate the no of days between two days

Formula-: now - Created Date


Thanks 
Raj
nagachandra knnagachandra kn
Hi Maharaja,

Please add this code after the trigger.new for loop in your TRIGGER and try to execute the test class once.

if(test.isRunningTest()){
        
        Days = 0;
    }

Thanks
-Nag
 
This was selected as the best answer
Maharajan CMaharajan C
Hi NagaChandra,

That Works...Great...Thanks for your help...We also made a some change...

If You Don't mind let me Know the Function of Above Coding
Waiting For Your Reply Nagachandra...


Just explain the concept of  

if(test.isRunningTest()){
         Days = 0;
    }


Thanks
Raj.
 
nagachandra knnagachandra kn
Hi Maharaja,
    
Test.isRunningTest() - Returns true if the currently executing code was called by code contained in a test method, false otherwise. so only when test class is executed then only days will be zero. otherwise that block of code wont execute and data will be fetched from custom settings.

Please select it as best answer so that it will help other people who might be facing same issue.

Thanks
-Nag
 
Maharajan CMaharajan C
Hi Nag,

Now i slightly Change my Code So can you u please help me to code coverge because i got only 43% coverage

trigger sendNotificationTrigger on CampaignMember (after insert) {
    Set<Id> LeadIds = new Set<ID>();
    Lead_Campaign__c tm;//Assinging Custom setting To the variable tm
    tm=Lead_Campaign__c.getorgdefaults();
    String Template=tm.Email_Template_ID__c;
    Decimal Days=tm.Threshold_Days__c;
     
    list <CampaignMember> theCampaignMembers = new list<CampaignMember>();
    for(CampaignMember campMem : Trigger.new){//
    if(test.isRunningTest()){
        
        Days = 0;
    }
        if(campMem.leadid != null){
            LeadIds.add(campMem.leadid);
            theCampaignMembers.add(campMem);
         
            }
    // List containing Campaign Member records to be inserted  
    List<Messaging.SingleEmailMessage> mails =new List<Messaging.SingleEmailMessage>();   
    for(Lead ld : [select id, Status,Lead_age__c, owner.email from Lead where id IN : LeadIds])
    try
    {

    if(ld.Status!='Qualified'&&ld.Lead_age__c>=Days)
    //Checking Condition Status not equal to Qualified and Lead_Age_In_days__c greater than equal to 30
    {
 
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();// For Email
                             
      List<String> sendTo = new List<String>();
      sendTo.add(ld.Owner.Email);//sending message via Email to the Owner of the lead
      mail.setToAddresses(sendTo);
      mail.saveAsActivity = false;
      mail.setTemplateId(Template);//Using custom setting field template as template id
      mail.setTargetObjectId(ld.OwnerId);    
      mail.setWhatId(ld.id);
      mails.add(mail);
      Messaging.sendEmail(mails);
  
}
}
 catch (Exception e)
{

  ApexPages.addMessages(e);
  Profile adminProfile = [Select id From Profile Where Name='System Administrator' Limit 1];

     Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
     List<String> toAddresses = new List<String>();
     toAddresses.add(adminProfile.id);
     mail.setToAddresses(toAddresses);
     mail.setSenderDisplayName('Apex error message');
     mail.setSubject('Error from Org : ' + UserInfo.getOrganizationName());
     mail.setPlainTextBody(e.getMessage());
     Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
  
}
}


Test Class -:

@isTest(SeeAllData = true)
public class sendNotificationTrigger
{
static testMethod void sendNotificationTrigger ()
{
     Test.startTest();      //Creates Contact to be linked to Campaign Member
Campaign cp =  [SELECT Id FROM Campaign LIMIT 1];
       //Creates a new campaign memeber, associaites it with 1 campaign
 Lead t1 = new Lead(Company= 'TestLead', LastName= 'TestL', Email = 'none@test.com',Status = 'Open' );
 insert t1;
 CampaignMember newMember = new CampaignMember (LeadId = t1.id, status='Sent', campaignid = cp.id);
 insert newMember;
 system.assertequals(t1.status,'Open')  ;

  
 
   
 Test.stopTest();
 }



Thanks
Raj