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
Terry WymanTerry Wyman 

Test class at 66% coverage in sandbox but 0% in production

I am trying to deploy a simple invocablemethod class to send emails out when a lead is added to a campaign.  I had used hard coded IDs which provided 100% coverage in the sandbox but 0% in production, I've removed the hardcoded references.  Any help is appreciated, my code and test class are below:
public class SendEmailToLead {
    @InvocableMethod
    public static void sendEmail(List<CampaignMember> CampaignMembers) {
        List<CampaignMember> thecampaignmembers = new List<Campaignmember>();
        for (CampaignMember cm : CampaignMembers) {
            List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setTargetObjectId(cm.LeadId);
            List<String> sendTo = new List<String>();
            sendTo.add(cm.Email);
            mail.setToAddresses(sendTo);            
            mail.setReplyTo('nomail@nomail.com');
            mail.setSenderDisplayName('nomail');       
            
           Campaign c = [SELECT Id FROM Campaign WHERE Name = 'some name' LIMIT 1];
       		 if(cm.CampaignId == c.Id) {
		    		EmailTemplate et=[Select id from EmailTemplate where DeveloperName=:'some name' LIMIT 1];
                    mail.setTemplateId(et.id);
                 	List<String> bccTo = new List<String>();
           			bccTo.add('nomail@nomail.com');
                 	bccTo.add('nomail@nomail.com');
            		bccTo.add('nomail@nomail.com');
            		bccTo.add('nomail@nomail.com');
            		mail.setBccAddresses(BccTo);
            }            
            Campaign c2 = [SELECT Id FROM Campaign WHERE Name = 'some name' LIMIT 1];
       		 if(cm.CampaignId == c2.Id) {
		    		EmailTemplate et2=[Select id from EmailTemplate where DeveloperName=:'some name' LIMIT 1];
                    mail.setTemplateId(et2.id);
                 	List<String> bccTo = new List<String>();
           			bccTo.add('nomail@nomail.com');                 	
            		bccTo.add('nomail@nomail.com');
            		bccTo.add('nomail@nomail.com');
            		bccTo.add('nomail@nomail.com');
            		mail.setBccAddresses(BccTo);
            } 
            mails.add(mail);
            Messaging.sendEmail(mails);                 
        }          
    }         
}
and the test class is below:
@isTest
// Tests the SendEmailToLead Trigger
public class TestSendEmailToCampaignMember {
static testMethod void ValidateSendEmailToCampaignMember() {
        Lead l = new Lead();
        l.FirstName = 'Testing';
        l.LastName = 'Lead';
        l.Company = 'Test Company';
        l.Industry = 'Banking';
        l.LeadSource = 'some source';
        l.Rating = 'Normal';
        l.Email = 'test@nomail.com';
        l.Street = '123 Main St';
        l.State = 'FL';
        l.PostalCode = '34202';
        l.Lead_Date__c = date.today();
        l.HasOptedOutOfEmail = False;
    	l.Internal_Comments__c = 'x';
    	l.Project_Details__c = 'x';
        insert l;             
        
    	Campaign c = new Campaign();
    	c.Name = 'some name';
    	c.Status = 'Planning';
    	c.Type = 'Seminar/Conference';
    	c.StartDate = date.today();
    	c.EndDate = date.today();
    	c.OwnerId = UserInfo.getUserId();
    	insert c;
    	 
      	CampaignMember cm = new CampaignMember();
    	cm.CampaignId = c.Id;
      	cm.LeadId = l.Id;    	
        cm.Status = 'Sent';
        insert cm;
        
        Lead l2 = new Lead();
        l2.FirstName = 'Testing2';
        l2.LastName = 'Lead2';
        l2.Company = 'Test Company2';
        l2.Industry = 'Banking';
        l2.LeadSource = 'some source';
        l2.Rating = 'Normal';
        l2.Email = 'test@nomail.com';
        l2.Street = '123 Main St';
        l2.State = 'FL';
        l2.PostalCode = '34202';
        l2.Lead_Date__c = date.today();
        l2.HasOptedOutOfEmail = False;
   		l2.Internal_Comments__c = 'x';
    	l2.Project_Details__c = 'x';
        insert l2;
    
    	Campaign c2 = new Campaign();
    	c.Name = 'some name';
    	c.Status = 'Planning';
    	c.Type = 'Seminar/Conference';
    	c.StartDate = date.today();
    	c.EndDate = date.today();
    	c.OwnerId = UserInfo.getUserId();
    	insert c2;
        
    	CampaignMember cm2 = new CampaignMember();
        cm2.LeadId = l2.Id;    	
        cm2.CampaignId = c2.Id;
        cm2.Status = 'Sent';
        insert cm2;
    }
}

I am hoping that it is something simple that I've missed.
Abhilash Mishra 13Abhilash Mishra 13
Hi Terry,
Try this,
@isTest
// Tests the SendEmailToLead Trigger
public class TestSendEmailToCampaignMember {
static testMethod void ValidateSendEmailToCampaignMember() {
        Lead l = new Lead();
        l.FirstName = 'Testing';
        l.LastName = 'Lead';
        l.Company = 'Test Company';
        l.Industry = 'Banking';
        l.LeadSource = 'some source';
        l.Rating = 'Normal';
        l.Email = 'test@nomail.com';
        l.Street = '123 Main St';
        l.State = 'FL';
        l.PostalCode = '34202';
        l.Lead_Date__c = date.today();
        l.HasOptedOutOfEmail = False;
    	l.Internal_Comments__c = 'x';
    	l.Project_Details__c = 'x';
        insert l;             
        
    	Campaign c = new Campaign();
    	c.Name = 'some name';
    	c.Status = 'Planning';
    	c.Type = 'Seminar/Conference';
    	c.StartDate = date.today();
    	c.EndDate = date.today();
    	c.OwnerId = UserInfo.getUserId();
    	insert c;
    	 
      	CampaignMember cm = new CampaignMember();
    	cm.CampaignId = c.Id;
      	cm.LeadId = l.Id;    	
        cm.Status = 'Sent';
        insert cm;
        
        Lead l2 = new Lead();
        l2.FirstName = 'Testing2';
        l2.LastName = 'Lead2';
        l2.Company = 'Test Company2';
        l2.Industry = 'Banking';
        l2.LeadSource = 'some source';
        l2.Rating = 'Normal';
        l2.Email = 'test@nomail.com';
        l2.Street = '123 Main St';
        l2.State = 'FL';
        l2.PostalCode = '34202';
        l2.Lead_Date__c = date.today();
        l2.HasOptedOutOfEmail = False;
   		l2.Internal_Comments__c = 'x';
    	l2.Project_Details__c = 'x';
        insert l2;
    
    	Campaign c2 = new Campaign();
    	c.Name = 'some name';
    	c.Status = 'Planning';
    	c.Type = 'Seminar/Conference';
    	c.StartDate = date.today();
    	c.EndDate = date.today();
    	c.OwnerId = UserInfo.getUserId();
    	insert c2;
        
    	CampaignMember cm2 = new CampaignMember();
        cm2.LeadId = l2.Id;    	
        cm2.CampaignId = c2.Id;
        cm2.Status = 'Sent';
        insert cm2;
      
      list<campaignMember> campMemList= new list<campaignMember>{ cm1,cm2};
      SendEMailToLead.sendEmail(campMemLIst);
       

    }

}

Hope this will work :)
 Let me know if you need more help.
Please mark the question solved  by selecting a best answer if it soves the issue.

Good luck :)
Adarsh.SharmaAdarsh.Sharma
Hi Terry Wyman,

Try This:

Apex class:
 
public class SendEmailToLead {
    @InvocableMethod
    public static void sendEmail(List<CampaignMember> CampaignMembers) {
        List<CampaignMember> thecampaignmembers = new List<Campaignmember>();
         List<String> sendTo = new List<String>();
        for (CampaignMember cm : CampaignMembers) {
            List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setTargetObjectId(cm.LeadId);
           if(!test.isRunningTest()){
               sendTo.add(cm.Email);
               }
               else{
                    sendTo.add('nomail@nomail.com');
                 }   
            mail.setToAddresses(sendTo);            
            mail.setReplyTo('nomail@nomail.com');
            mail.setSenderDisplayName('nomail');
            mail.setPlainTextBody('');       
            
           Campaign c = [SELECT Id FROM Campaign WHERE Name = 'some name' LIMIT 1];
             if(cm.CampaignId == c.Id) {
                    EmailTemplate et=[Select id from EmailTemplate where DeveloperName='myTemp' LIMIT 1]; //replace myTemp with your Template Name
                    mail.setTemplateId(et.id);
                    mail.setPlainTextBody('');
                    List<String> bccTo = new List<String>();
                    bccTo.add('nomail@nomail.com');
                    bccTo.add('nomail@nomail.com');
                    bccTo.add('nomail@nomail.com');
                    bccTo.add('nomail@nomail.com');
                    mail.setBccAddresses(BccTo);
            }            
            Campaign c2 = [SELECT Id FROM Campaign WHERE Name = 'some name' LIMIT 1];
             if(cm.CampaignId == c2.Id) {
                    EmailTemplate et2=[Select id from EmailTemplate where DeveloperName='myTemp' LIMIT 1];//replace myTemp with your Template Name
                    mail.setTemplateId(et2.id);
                    mail.setPlainTextBody('');
                    List<String> bccTo = new List<String>();
                    bccTo.add('nomail@nomail.com');                     
                    bccTo.add('nomail@nomail.com');
                    bccTo.add('nomail@nomail.com');
                    bccTo.add('nomail@nomail.com');
                    mail.setBccAddresses(BccTo);
            } 
            mails.add(mail);
            Messaging.sendEmail(mails);                 
        }          
    }         
}





TestClass:
@isTest
// Tests the SendEmailToLead Trigger
public class TestSendEmailToCampaignMember {

static testMethod void ValidateSendEmailToCampaignMember() {
                
         
        
        Campaign c = new Campaign();
        c.Name = 'some name';
        c.Status = 'Planning';
        c.Type = 'Seminar/Conference';
        c.StartDate = date.today();
        c.EndDate = date.today();
        c.OwnerId = UserInfo.getUserId();
        insert c;
        
        Lead l2 = new Lead();
        l2.FirstName = 'Testing2';
        l2.LastName = 'Lead2';
        l2.Company = 'Test Company2';
        l2.Industry = 'Banking';
        l2.LeadSource = 'some source';
        l2.Rating = 'Normal';
        l2.Email = 'test@nomail.com';
        l2.Street = '123 Main St';
        l2.State = 'FL';
        l2.PostalCode = '34202';
        //l2.Lead_Date__c = date.today();
        l2.HasOptedOutOfEmail = False;
        
        //l2.Internal_Comments__c = 'x';
        //l2.Project_Details__c = 'x';
        insert l2;
         
        
        list<CampaignMember>lstCampaignMember = new list<CampaignMember>();
        CampaignMember cm2 = new CampaignMember();
        cm2.LeadId = l2.Id;     
        cm2.CampaignId = c.Id;
        cm2.Status = 'Sent';
        lstCampaignMember.add(cm2);
        insert lstCampaignMember ;
        
        SendEmailToLead.sendEmail(lstCampaignMember);
    }
}


Hope this helps you!

If this helps you, please mark it as solved so that it will be available for others as a proper solution.

Thanks
Adarsh
Terry WymanTerry Wyman
Thank you both for responding, both responses helped, Adarsh, I missed the "cm2" change, I am currently at 75% coverage.  there is another issue as well...when I try to push the code into production, I get an error that states that the To email address is blank which comes from the Campaign Member Email address.  I checked the debug logs and found that the campaign member email address isn't populating with the lead email address...I don't know how to solve for this...the lead is successfully created with an email address, the campaign member is also created...but the email address wasn't passed.  It's a read only field, that self populates when the Id is passed...any thoughts
Abhilash Mishra 13Abhilash Mishra 13
Well that just seem unusual, the email field will definately populate. if the lead is added as member.

Ok, I have given A look on your code of sending Email. That does not seem to perfectly alright ( I might be wrong about that). 
What i Belive is SetTargetobjectid() and setTempateid() id used together to link a target object  with specified template. and there is no need to specify sendTo , as the email will be sent to the email of the Targetobject.
While sendto, setreplyTo() these methods are used when you define email body in code.

Are you sure, your Code sends email to the right person with right template. Becuase if test case showing this error. there must be something wrong with the actual class.

Regards
--Abhilash

 
Terry WymanTerry Wyman
Abhilash, 

you are right regarding the sendTo variable, it is included in the template...I took that line out...The difficult part is, it executes just fine...
 
Terry WymanTerry Wyman
Here is where I am at now: I'm getting an error "List has no rows for assignment to SObject, which points to the Class SOQL query on line 26: Campaign c2 = [SELECT Id FROM Campaign WHERE Name = 'some name' LIMIT 1];  I've run this query in the workbench and it returns the Id...so it clearly is there...I don't know if it's how the code is structured or not...
Abhilash Mishra 13Abhilash Mishra 13
This eror should have come at line  21: first. as you are using the same Query again.
 do you have email templates that have Developer name some name ?
Terry WymanTerry Wyman
I do have different templates in my code...I just didn't spell it out here there are two...each name is different and I can soql query both...I should have said some_name1 and some_name2
Terry WymanTerry Wyman
While there is quite a bit of information which may not apply to my situation, I believe there are a couple of issues...1.) I read that assigning a query to an SObject will cause an error, if I assign a list to an Sobject, it will work, 2.) but then I need be able to assign values to the Id fields allowing me to call out the actual Id field, 3.) lastly, I believe that when the test is called, the first inserted record would match the first If statement but because it doesn't match the second if statement it throughs another error.  what I believe that I need help with is how to code for calling "Campaign c" into a list and how to assign the Id field so that I can call it later in the code like: "if(cm.CampaignId == c.Id)" the last part that I need help with is accounting for the scenario where the "If" statement outputs a null value, none of the examples on the forum explain clearly how this is done...

Thank you to everyone who has helped thus far.