• Nelson Chisoko 3
  • NEWBIE
  • 0 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 0
    Replies
Hi Guys

Im trying to do apex code for converting emails to leads. I have configured my classes as follows but I cant seem to test them and in turn the whole thing does not work. Could anyone assist...im new to Apex Development:
/**
 * Email services are automated processes that use Apex classes
 * to process the contents, headers, and attachments of inbound
 * email.
 */
global class EmailReceive implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Lead lead;
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();        
        try {
            //Look for lead whos name is the email and create it if necessary
            if ([select count() from Lead where Name = :email.FromAddress] == 0) {
                    lead = new Lead();
                    lead.LastName = email.FromAddress;
                    lead.Email = email.FromAddress;
                    insert lead;
            } else { //Lead already exists
                lead = [select Id from Lead where Name = :email.FromAddress];
            }            
            result.success = true;
        } catch (Exception e) {
            result.success = false;
            result.message = 'Error processing email...';
        }
        return result;
    }
}
Below is my testing class
@isTest
private class EmailReceiveTest {
    static testMethod void myUnitTest() {
        // Create a new email and envelope object
        Messaging.InboundEmail email  = new Messaging.InboundEmail();
        Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
        //Create the email body
        email.plainTextBody = 'This should become a note';
        email.fromAddress = 'test@test.com';
        String contactEmail = 'jsmith@salesforce.com';
        email.subject = 'Dummy Account Name 123';
        
        EmailReceive er = new EmailReceive();
        
        Test.startTest();
        Messaging.InboundEmailResult result = er.handleInboundEmail(email, env);
        Test.stopTest();
        
        System.assert (result.success, 'InboundEmailResult returned a failure message');
        
        Lead [] leadDb = [SELECT Id FROM Lead where LastName=:email.FromAddress];
        System.assertEquals (1, leadDb.size(),'Lead was not inserted');
    }
}