Search code examples
salesforceapex-code

what is wrong with my test class in apex force.com code?


I have written a working class in Apex. It is an Email service extender, that processes incoming emails. It is working perfect on my sandbox enviroment.

I have created a test class, so I can also deploy it to my production, but when validating the code, I get the only 72% of my code is tested.

This is my main class

global class inboundEmail implements Messaging.InboundEmailHandler {

global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
    Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();

Lead lead;

String [] mFromUserParams;
String [] sourceText;
String mCaseObject; 

try{
    sourceText = email.toAddresses[0].split('@');
    String [] mParams = sourceText[0].split('\\.');
**// FROM THIS LINE TO THE END - NOT COVERED**
    mFromUserParams = email.fromAddress.split('@');
    mCaseObject = mParams[0];
    if (mCaseObject == 'lead'){
        lead = new Lead();
        lead.LastName = mFromUserParams[0];
        lead.Company = email.fromAddress;
        lead.OwnerId = mParams[1];
        lead.LeadSource = mParams[2];
        lead.Email = email.fromAddress;
        lead.RequirementsDescription__c = email.subject + email.plainTextBody;

        insert lead;
        result.success = true;
    }  else if (mCaseObject == 'case'){
        result.success = true;
    }  else {
        result.success = false;
    }
}catch(Exception e){
    result.success = false;
    result.message = 'Oops, I failed.';
}
return result;
}
}

This is my test class

@isTest
private class inboundEmailTest {
public static testMethod void inboundEmail(){     
    // Create a new email, envelope object and Header
    Messaging.InboundEmail email = new Messaging.InboundEmail();
    Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
envelope.toAddress = '[email protected]';
    envelope.fromAddress = '[email protected]';
    email.subject = 'Please contact me';
    email.fromName = 'Test From Name';
    email.plainTextBody = 'Hello, this a test email body. for testing  Bye';
    // setup controller object
    inboundEmail catcher = new inboundEmail();
    Messaging.InboundEmailResult result = catcher.handleInboundEmail(email, envelope);
}
}

According to the error message, ALL lines in the Try/Catch block from the 3rd line are not covered. (marked in the code).


Solution

  • The email.fromAddress is not a list by default, so just setting that to a string and not a list solved this.