+ Start a Discussion
etessetess 

Test Methods for Messaging.SingleEmailMessage ~

I have a controller (ex. myController) with a method (ex. mailMyContact), that when called, sends an e-mail (Messaging.SingleEmailMessage) with a PDF attachment (saved from a VF page). This is working fine in the Sandbox - the method is called from a User button click from a visualforce page. However, I can't figure out how to test it. I'm trying the below - when I comment out the third line it the coverage covers the other method, but when I include it, it's not getting any coverage. Is there a trick to testing Single Email Messages and/or PDF attachments?

 

 

myController c = new myController();
c.updateContact();
c.mailMyContact();

 

 

Best Answer chosen by Admin (Salesforce Developers) 
etessetess

I got around this by only attaching the PDF under certain conditions, so that in my test I am not attaching anything to the e-mails. Kind of a hack, but it works.

All Answers

etessetess

So, it appears the issue is that simply calling the method is throwing the following error:

System.VisualforceException: Methods defined as TestMethod do not support getContent call, test skipped

 

However, if I try/catch for that exception in my call (c.mailMyContact()), it just skips testing the method -

 

How do I get coverage?

etessetess

I got around this by only attaching the PDF under certain conditions, so that in my test I am not attaching anything to the e-mails. Kind of a hack, but it works.

This was selected as the best answer
FinnArildFinnArild

Another way of doing this is to select an attachment you already have in the database (provides that you have, but that should be easily enough provided).

 

So where "agr" is the object you want to add an attachment to:

 

        Attachment atchoo = [Select Id, Body From Attachment where Name like '%.pdf' LIMIT 1];
    	Attachment prosit = new Attachment(Name='kalle.pdf', ParentId=agr.Id, Body=atchoo.Body); 
    	insert prosit;