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
viktorVviktorV 

testing outbound email

I've got a lead detail page button which opens a VF page with most important lead details. Clicking on Send on VF page runs my class which sends out the email the given address.

The class works right, but I'm newbie and cannot create the test method.

VF code:

 

<apex:page standardController="Lead" extensions="sendLeadInEmail" title="Send Lead in Email">
 <apex:form >
     <apex:sectionHeader title="Send Lead in email to a specified person"/>
     <apex:pageBlock mode="edit" >
         <apex:messages />
         <apex:pageBlockSection title="Lead details">
                <apex:pageBlockTable value="{!lead}" var="lead">
                    <apex:column value="{!lead.Name}"></apex:column>
                    <apex:column value="{!lead.Company}"></apex:column>
                    <apex:column value="{!lead.Title}"></apex:column>
                    <apex:column value="{!lead.Phone}"></apex:column>
                    <apex:column value="{!lead.Email}"></apex:column>
                    <apex:column value="{!lead.Street}"></apex:column>
                    <apex:column value="{!lead.City}"></apex:column>
                    <apex:column value="{!lead.State}"></apex:column>
                    <apex:column value="{!lead.PostalCode}"></apex:column>
                    <apex:column value="{!lead.Country}"></apex:column>
                    <apex:column value="{!lead.Website}"></apex:column>
                    <apex:column value="{!lead.Product__c}"></apex:column>
                    <apex:column value="{!lead.CreatedDate}"></apex:column>
               </apex:pageBlockTable>
         </apex:pageblockSection>
         <apex:pageblockSection title="Name of Recipient">
                <apex:inputText value="{!recipient}" id="Recipient" maxlength="80" required="true" />
         </apex:pageBlockSection>
         <apex:pageblockSection title="Email address">
                <apex:inputText value="{!address}" id="Address" maxlength="80" required="true"/>
         </apex:pageBlockSection>
         <apex:pageBlockSection title="Personal message (optional)"  >
                <apex:inputTextarea value="{!comment}" id="Comment" required="false" cols="75" rows="6"/>
         </apex:pageBlockSection>
         <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Send Email" action="{!send}" />                        
                <apex:commandButton value="Cancel" action="{!cancel}"/>
         </apex:pageBlockButtons>
    </apex:pageBlock>    
  </apex:form>
</apex:page>

APEX Class code:

 

public class sendLeadInEmail {
 
	public String recipient{ get; set; }
	public String address { get; set; }
 	public String comment { get; set; }
 	public String plainPersonalMessage;
 	public String htmlPersonalMessage;
 	public String subject;
 	public String plainTextBody;
 	public String htmlBody;
 	public String Title, Phone, EmailAddress, Street, City, State, PostalCode, Country, Website, Product;
 
	private final Lead lead;
 
 	// Create a constructor that populates the Lead object
	public sendLeadInEmail(ApexPages.StandardController controller) {
  		lead = [select Name, Company, Title, Phone, Email, Street, City, State, PostalCode, Country, Website, Product__c, CreatedDate, Sent_in_Email_to__c
    			from Lead where id = :ApexPages.currentPage().getParameters().get('id')];
 	}
  
	 
 	public PageReference send() {
  		// Define the email
  		Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
 		   
  		subject = 'Lead details';
	
  		if (lead.Title == null) Title = ''; else Title = lead.Title;
  		if (lead.Phone == null) Phone = ''; else Phone = lead.Phone;
  		if (lead.Email == null) EmailAddress = ''; else EmailAddress = lead.Email;
  		if (lead.Street == null) Street = ''; else Street = lead.Street;
  		if (lead.City == null) City = ''; else City = lead.City+',';
  		if (lead.State == null) State = ''; else State = lead.State;
  		if (lead.PostalCode == null) PostalCode = ''; else PostalCode = lead.PostalCode;
  		if (lead.Country == null) Country = ''; else Country = lead.Country;
  		if (lead.Website == null) Website = ''; else Website = lead.Website;
  		if (lead.Product__c == null) Product = ''; else Product = lead.Product__c;
 
	  	plainPersonalMessage = comment;
  		htmlPersonalMessage = comment;
 
 	 	if (plainPersonalMessage != '') plainPersonalMessage = comment + '\n\n';
  		if (htmlPersonalMessage != '') htmlPersonalMessage = '<pre><font face="times,times new roman,liberation sans,liberation serif,helvetica,arial,sans,serif" size="4">' + comment + '</font></pre><br>';
  
  		plainTextBody = 'Dear '
  			+ recipient + ',\n\n' + plainPersonalMessage + /* ... */ + 'Best regards,';
  
    	htmlBody = '<font face="times,times new roman,liberation sans,liberation serif,helvetica,arial,sans,serif" size="4">Dear ' + recipient + ',<br><br>' +
  	 		htmlPersonalMessage + /* ... */ + 'Best regards,</font>';
  
		String[] toAddresses = address.split(',',0);          
  		String bccAddress = /* ... */;
  		String[] bccAddresses = bccAddress.split(',',0);  
		
  		// Sets the paramaters of the email
 		email.setSubject( subject );
  		email.setToAddresses( toAddresses );
  		email.setPlainTextBody( plainTextBody );
  		email.setHtmlBody( htmlBody );
	  
	  	// Sends the email
  		Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
		
		//set the 'Sent in Email to' field on related Lead:
  		if (lead.Sent_in_Email_to__c == null) lead.Sent_in_Email_to__c = recipient + ' (' + address + ')';
  		else lead.Sent_in_Email_to__c += ', ' + recipient + ' (' + address + ')';
  		update lead;

		// After email sent, navigate to the default view page:
  		return (new ApexPages.StandardController(lead)).view();

	}
	  			

 	static testMethod void myTest() {
       	Lead l = new Lead(
       		FirstName = 'testFirst',
       		LastName = 'testLast',
       		Company ='testcompany',
       		Title = 'testTitle',
       		Phone = '1234',
       		Email = 'test@email.com',
       		Street = 'testStreet',
       		City = 'testCity',
       		State = 'testState',
       		PostalCode = 'testPostal',
       		Country = 'testCountry',
       		Website = 'testWebsite',
       		Product__c = 'testProduct');
		insert l;
		
		Lead testL = [SELECT Id FROM Lead WHERE FirstName = 'testFirst'];
		PageReference leadPage = new PageReference('partialURL');
 		Test.setCurrentPage(leadPage);
		ApexPages.currentPage().getParameters().put('id',testL.Id);
		
		Id testID = ApexPages.currentPage().getParameters().get('id');
		System.assertEquals(testID,testL.Id);
		

		// Instantiate String_function controller
   		ApexPages.StandardController s = new ApexPages.standardController(testL);
   		sendLeadInEmail testSend = new sendLeadInEmail(s);
   		testSend.send();
        
 	}

}

 running the testSend.send(); line gives the next error:

System.NullPointerException: Attempt to de-reference a null object.

 

Where should I set to test the appropriate object?

 

thanks,

Viktor

 

 

Best Answer chosen by Admin (Salesforce Developers) 
viktorVviktorV

I've solved the problem!

The controller1.address, controller1.recipient and controller1.comments fields were blank. I gave them value and worked

All Answers

Pradeep_NavatarPradeep_Navatar

Try out the sample code given below :

 

                                                static testMethod void myTest()

                                                {

                                                                Lead l = new Lead

                                                                (

                                                                                FirstName = 'testFirst',

                                                                                LastName = 'testLast',

                                                                                Company ='testcompany',

                                                                                Title = 'testTitle',

                                                                                Phone = '1234',

                                                                                Email = 'test@email.com',

                                                                                Street = 'testStreet',

                                                                                City = 'testCity',

                                                                                State = 'testState',

                                                                                PostalCode = 'testPostal',

                                                                                Country = 'testCountry',

                                                                                Website = 'testWebsite',

                                                                                Product__c = 'testProduct'

                                                                );

                                                                insert l;

 

                                                                ApexPages.CurrentPage().getParameters().put('id',l.Id);

                                                                ApexPages.StandardController controller1 = new ApexPages.StandardController(l);

                                                                sendLeadInEmail  sendemail = new sendLeadInEmail(controller1);

                                                                PageReference prf = sendemail.send();

                                                }

 

Hope this helps.

viktorVviktorV

Still getting error, just for PageReference prf = sendEmail.send();

Maybe  public PageReference send() { ... } needs a parameter??

viktorVviktorV

I've solved the problem!

The controller1.address, controller1.recipient and controller1.comments fields were blank. I gave them value and worked

This was selected as the best answer
BialBial

Hi

I am facing problems in testing outbound email trigger. Please help me to sort out this issue.the following are the codes i.e. trigger code and test code, but test code give error.kindly suggest me test code or help in removing the error.

 

 

trigger sendemaildemo on Case (after insert, after update) {

final String template = 'Test';
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();

Messaging.SingleEmailMessage message1 = new Messaging.SingleEmailMessage();

Messaging.SingleEmailMessage message2 = new Messaging.SingleEmailMessage();

Messaging.SingleEmailMessage message3 = new Messaging.SingleEmailMessage();

Messaging.SingleEmailMessage message4 = new Messaging.SingleEmailMessage();

 

message.setTemplateId([select id from EmailTemplate where Name =:template].id);

message1.setTemplateId([select id from EmailTemplate where Name =:template].id);

message2.setTemplateId([select id from EmailTemplate where Name =:template].id);

message3.setTemplateId([select id from EmailTemplate where Name =:template].id);

message4.setTemplateId([select id from EmailTemplate where Name =:template].id);

 

 

// Send single mail to contact of each updated case
for (Case uc: Trigger.new) {

Contact c = [select Email from Contact where Id =:uc.ContactId and Email!=null];

message.setTargetObjectId(c.Id);
message.setWhatId(uc.Id);

message.setToAddresses(new String[] {c.Email});
Messaging.sendEmail(new Messaging.Email[] {message});
}

for (Case vc: Trigger.new) {
IF (vc.Contactemail__c!=null){
Contact v = [select Email from Contact where Id =:vc.Contact__c and Email != null];

message1.setTargetObjectId(v.Id);
message1.setWhatId(vc.Id);

message1.setToAddresses(new String[] {v.Email});
Messaging.sendEmail(new Messaging.Email[] {message1});
}
IF (vc.Contact2email__c!=null) {
Contact b = [select Email from Contact where Id =:vc.Contact2__c and Email != null];

message2.setTargetObjectId(b.Id);
message2.setWhatId(vc.Id);

message2.setToAddresses(new String[] {b.Email});
Messaging.sendEmail(new Messaging.Email[] {message2});


}
IF (vc.Contact3email__c!=null) {
Contact d = [select Email from Contact where Id =:vc.Contact3__c and Email != null];

message3.setTargetObjectId(d.Id);
message3.setWhatId(vc.Id);

message3.setToAddresses(new String[] {d.Email});
Messaging.sendEmail(new Messaging.Email[] {message3});

}


IF (vc.Contact4email__c!=null) {
Contact f = [select Email from Contact where Id =:vc.Contact4__c and Email != null];

message4.setTargetObjectId(f.Id);
message4.setWhatId(vc.Id);

message4.setToAddresses(new String[] {f.Email});
Messaging.sendEmail(new Messaging.Email[] {message4});
}

else {
}

}
}

 

 

 

Test Code:

 

/**
* This class contains unit tests for validating the behavior of Apex classes
* and triggers.
*
* Unit tests are class methods that verify whether a particular piece
* of code is working properly. Unit test methods take no arguments,
* commit no data to the database, and are flagged with the testMethod
* keyword in the method definition.
*
* All test methods in an organization are executed whenever Apex code is deployed
* to a production organization to confirm correctness, ensure code
* coverage, and prevent regressions. All Apex classes are
* required to have at least 75% code coverage in order to be deployed
* to a production organization. In addition, all triggers must have some code coverage.
*
* The @isTest class annotation indicates this class only contains test
* methods. Classes defined with the @isTest annotation do not count against
* the organization size limit for all Apex scripts.
*
* See the Apex Language Reference for more information about Testing and Code Coverage.
*/
@isTest
private class sendemaildemo {

static testMethod void myUnitTest() {
// TO DO: implement unit test
Case caset = new Case ();
caset.Origin = '2F5008000000IEE2g';
caset.Status = 'New';
caset.Origin = 'CheseTek';
caset.ContactId = '0038000001Doy5g';
caset.Contact__c = '0038000001Doy5g';
caset.Contact2__c = '0038000001Doy5g';
caset.Contact3__c = '0038000001Doy5g';
caset.Contact4__c = '0038000001Doy5g';

insert caset;

caset.Contact2__c = '0038000001Doy5g';
update caset;


}
}

 

 

Error:

Error in test code 
insert caset.

 

 

Please help me ASAP

 

Thanks in Advance!