+ Start a Discussion
sales4cesales4ce 

Help needed with a Test method for email to apex

Hi,

 

I am stuck with developing a testmethod for email to apex.

I tried to follow the example but to no luck.

 

What my email to apex does is:

 

1) after receiving the email , which is of following format:

Firstname : test

lastname : test

e-mail address : test@test.com

 

2) i check if there is already a existing contact using email address

3) if there is a matching email address, i shall go and create a new task to that matched contact.

4) If no match is found i shall create a contact and then create a ceate a new task to that contact.

 

Can any one help me with the test method.

 

for code , pls look at this link:

http://community.salesforce.com/t5/Apex-Code-Development/Email-to-Apex-Test-method/td-p/181756

 

sorry for duplicate post, but need help on this.

 

Thanks,

Sales4ce

Hi,

 

I am developing email to apex functionality for my use case and was able to develop.

But what i am stuck with is the Test method. I have tried to follow some examples from book but no luck as the test method does not compile. Can anybody help me with this.

 

What my Email to apex does:

 

It reads and email, which is of this format(In Red):

 

First Name : Dave

Last name : Williams

E-mail Address : dwilliams@test.com

 

it reads the values and then creates a contact if there is no contact ( i do the checking based on the email).

After a contact is created, it creates an associated task.

Incase, we find a contact, then we create a task to that contact itself.

 

Below is My apex code:

 

global class ProcessApplicants implements
Messaging.InboundEmailHandler
{

    contact[] mycontact=new contact[0];
    
    global Messaging.InboundEmailResult handleInbo undEmail
    (Messaging.InboundEmail email,Messaging.Inboun dEnvelope env)
    {
        Messaging.InboundEmailResult result = new  Messaging.InboundEmailresult();
        string emailaddress=env.fromaddress;
        string e_Subject=email.Subject;
        string[] emailbody=email.plainTextBody.spl it('\n',0);
        string fname=emailbody[0].substring(12);
        string lname=emailbody[1].substring(11);
        string c_email=emailbody[2].substring(16);
        Datetime start_time=Datetime.Now();
        Datetime end_time=start_time.addhours(2);
        
        Contact inserted_Contact;
        contact existing_Contact;
                
        System.Debug('Email address after substrin g =='+c_email);
        try
        {
            //Contact[] existing_Contacts=[Select  Id,email from Contact where email=:c_email limit 1 ];
            existing_Contact=[Select Id from Conta ct where email=:c_email limit 1];
            //existing_Contact=existing_Contacts[0 ];
            system.debug('Contact Id=='+existing_C ontact.Id);
            if(e_Subject=='Registration Day')
            {
                Task[] myTask=new Task[0];
                myTask.add(new Task(Description='T esting Purpose',Subject='Make a Call',Priority='No rmal',Status='Not Started',WhoId=existing_Contact. Id));
                insert myTask;
             }
             else
             {
                 Event[] myEvent=new Event[0];
                 myEvent.add(new Event(Subject='Ju nior Day',WhoId=existing_Contact.Id,EndDateTime=en d_time,StartDateTime=start_time));
                 insert myEvent;
             }
        }
        
        catch(exception ex)
        {
            try
            {
              mycontact.add(new contact(FirstName= fname,LastName=lname,email=c_email));
              insert mycontact;
              inserted_Contact=mycontact[0];
          
              System.Debug('Contact Id_New=='+inse rted_Contact.Id);
              if(e_Subject=='Registration Day')
              {
                  Task[] myTask= new Task[0];
                  myTask.add(new Task(Description= 'Testing Purpose',Subject='Make a Call',Priority=' Normal',Status='Not Started',WhoId=inserted_Contac t.Id));
                  insert myTask;
              }
              else
              {
                 Event[] myEvent=new Event[0];
                 myEvent.add(new Event(Subject='Ju nior Day',WhoId=inserted_Contact.Id,EndDateTime=en d_time,StartDateTime=start_time));
                 insert myEvent;
              }
            }
        
            Catch(DMLException e)
            {
                System.Debug('Error in creating co ntact:'+e);
            }
         }
         
         
         
        
                                                                                                                                                
return result;
}
}

 

Here is My test method:

 

Static testMethod void testTasks()
    {
        Messaging.InboundEmail email = new Messagi ng.InboundEmail();
        Messaging.InboundEnvelope env = new Messag ing.InboundEnvelope();

        email.plainTextBody='Test, Last, TLast@email.com, july 2010';
        email.fromaddress='Sales4ce@gmail.com ';
        email.Subject='Registration Day';
        string[] emailbody=email.plainTextBody.spl it(',',0);
        string fname=emailbody[0];
        string lname=emailbody[1];
        string c_email=emailbody[2];
        string grad_day=emailbody[3];

 

This is the error msg:

Compile Error: Method does not exist or incorrect signature: [SOBJECT:Task].handleInboundEmail(Messaging.Inboun dEmail, Messaging.InboundEnvelope) at line 94 column 8

 

This test method is included with in the same class above.

 

Thanks,

Sales4ce

Best Answer chosen by Admin (Salesforce Developers) 
NaishadhNaishadh

Here is the code with 100% code coverage.

global class ProcessApplicants implements Messaging.InboundEmailHandler
{
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
                                            Messaging.InboundEnvelope env)
    {
        Messaging.InboundEmailResult result = new  Messaging.InboundEmailresult();
        string emailaddress=env.fromaddress;
        string e_Subject=email.Subject;
        String[] emailbody=email.plainTextBody.split('\n',0);
        System.debug(emailbody);
        
        return null;
    }
    
    public static testMethod void ProcessApplicants() {
        Messaging.InboundEmail email = new Messaging.InboundEmail();
        Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
        
        email.subject = 'test';
        email.fromAddress = 'naishadh123@abc.com';
        String body = 'First Name : Dave ' + '\n' + 'Last name : Williams' + '\n' + 
                            'E-mail Address : dwilliams@test.com';
        email.plainTextBody =  body;
        
        
        ProcessApplicants emailServiceObj = new ProcessApplicants();
        emailServiceObj.handleInboundEmail(email, env ); 
    }
}

 

 

All Answers

NaishadhNaishadh

Following are the step for code coverage

1. create contact with abc@abc.com

2. send email using above email address

3. send another email with abc1@abc.com so that it will first create contact and then add task into it.

 

Error your are getting List index out of bound exception is due to following line

 

existing_Contact=[Select Id from Conta ct where email=:c_email limit 1];
replace this with
List<Contact> conList = [Select Id from Contact where email = :c_email limit 1];
sales4cesales4ce

Hi Naishadh,

 

Thanks for your reply/help.

Eventually now i am able to save the class, but unable to achieve the code coverage.

 

For some reason it is not recognizing my email address in code coverage.

 

My email format is like this:

firstname : somename

Lastname : somename

e-mail address : some@email.com

 

in test method, we send an email as plaintextbody, so i am doing it this way:

 

email.plainTextBody='FirstName: Test,LastName: test,Email Address : Test@mysales.com';

 

So i need to break this using a delimiter "Comma" into new line. for this i am doing this way:

 

 string[] emailbody=email.plainTextBody.split(',',0);

 

But for some reason i don't know why its not giving code coverage.

Am i doing anything wrong?

 

Thanks,

Sales4ce

 

ahab1372ahab1372

did you fix the error you mentioned in the other post? I suggest you insert some System.Debug() statements, for example for the emailbody, to see what happens?

NaishadhNaishadh

If Ok paste your code.

NaishadhNaishadh

Here is the code with 100% code coverage.

global class ProcessApplicants implements Messaging.InboundEmailHandler
{
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
                                            Messaging.InboundEnvelope env)
    {
        Messaging.InboundEmailResult result = new  Messaging.InboundEmailresult();
        string emailaddress=env.fromaddress;
        string e_Subject=email.Subject;
        String[] emailbody=email.plainTextBody.split('\n',0);
        System.debug(emailbody);
        
        return null;
    }
    
    public static testMethod void ProcessApplicants() {
        Messaging.InboundEmail email = new Messaging.InboundEmail();
        Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
        
        email.subject = 'test';
        email.fromAddress = 'naishadh123@abc.com';
        String body = 'First Name : Dave ' + '\n' + 'Last name : Williams' + '\n' + 
                            'E-mail Address : dwilliams@test.com';
        email.plainTextBody =  body;
        
        
        ProcessApplicants emailServiceObj = new ProcessApplicants();
        emailServiceObj.handleInboundEmail(email, env ); 
    }
}

 

 

This was selected as the best answer
sales4cesales4ce

Hi Naishadh,

 

Thanks for the help! It worked for me like charm!

 

Sales4ce