如何为Messaging.SingleEmailMessage apex类编写测试类?

时间:2015-03-16 11:22:14

标签: salesforce apex-code test-coverage

我编写了以下Apex类,用于处理发送到电子邮件服务地址的传入电子邮件,并从传入邮件创建新任务,然后将此新任务与salesforce中的匹配记录相关联。匹配是在记录名称和传入电子邮件主题上完成的。该课程还会发送一封电子邮件,通知"分配给"用户,他们已收到他们正在处理的请求的回复。

这在Sandbox中非常完美,但我没有编写测试类的经验。任何人都可以建议我如何编写下面的测试类?

global class RequestEmailHandler implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
    Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
    String myPlainText = email.plainTextBody;
    String subject = email.fromName + ' - ' + email.subject;
    system.debug(email);

    subject = subject.left(255);
    Request__c request;


    if (subject != null && subject.trim().length() > 0 && subject.indexOf('(R-') > 0) {
        Integer idx = subject.indexOf('(R-');
        String requestName = subject.substring(idx+1, subject.indexOf(')', idx));
        request = [SELECT Id, Assigned_To__c FROM Request__c WHERE Name = :requestName];
    }

    if (request == null) {
        result.message = 'We were unable to locate the associated request.This may be due to the unique "R" number being removed from the subject line.\n Please include the original email subject when replying to any emails.';
        result.success = false;
        return result;
    }            

    // Add the email plain text into the local variable       
    Task task = new Task(
       WhatId = request.Id,
       Description =  myPlainText,
       Priority = 'Normal',
       Status = 'Completed',           
       Type = 'Email',
       Subject = subject,
       ActivityDate = System.today(),
       RecordTypeId = '01250000000HkEw');
    insert task;


    //Find the template
    EmailTemplate theTemplate = [select id, name from EmailTemplate where DeveloperName = 'New_Email_Reply2'];
    //Create a new email right after the task
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

    //Add email To addresses to list
    List<String> toAddresses = new List<String>();
    toAddresses.add(email.fromAddress);
    //Set the list of to addresses
    mail.setToAddresses(toAddresses);
    //Set the template id
    mail.setTemplateId(theTemplate.id);
    //The Id of the user
    mail.setTargetObjectId(request.Assigned_To__c);
    //Set the id of the request
    mail.setWhatId(request.Id);
    //If you need the email also saved as an activity, otherwise set to false
    mail.setSaveAsActivity(false);   

    //Send Email
    try {
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
    }
    catch (EmailException e) {
        system.debug('sendEmail error: ' + e.getMessage());
    }


    // Save attachments, if any
    if (email.textAttachments != null)
    {
        for(Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments)
        {
            Attachment attachment = new Attachment();

            attachment.Name = tAttachment.fileName;
            attachment.Body = Blob.valueOf(tAttachment.body);
            attachment.ParentId = request.Id;
            insert attachment;
        }

    }

    //Save any Binary Attachment
    if (email.binaryAttachments != null)
    {
        for(Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
            Attachment attachment = new Attachment();

            attachment.Name = bAttachment.fileName;
            attachment.Body = bAttachment.body;
            attachment.ParentId = request.Id;
            insert attachment;    
            return result;
        }
    }
    return result;
}

}

以下是我的尝试,只获得24%的报道。我知道它缺少重要的代码,但我对测试类的了解还不够深入。

有人可以帮忙吗?

测试类

@isTest
public class testforemail  {
    static testMethod void insertRequest() {

       Request__c requestToCreate = new Request__c();

       requestToCreate.Subject__c= 'test';
       requestToCreate.Requested_By_Email__c= 'graham.milne@fmr.com';

       insert requestToCreate;   



        Messaging.InboundEmail email = new Messaging.InboundEmail();
        Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();

       Request__c testRequest = [select Id,Name from Request__c limit 1]; 
       System.debug(testRequest.Name);



        email.subject = (testRequest.Name);
        email.fromName = 'test test';
        email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:123456 Bye';
        Messaging.InboundEmail.BinaryAttachment[] binaryAttachments = new Messaging.InboundEmail.BinaryAttachment[1];  
        Messaging.InboundEmail.BinaryAttachment binaryAttachment = new Messaging.InboundEmail.BinaryAttachment();
        binaryAttachment.Filename = 'test.txt';
        String algorithmName = 'HMacSHA1';
        Blob b = Crypto.generateMac(algorithmName, Blob.valueOf('test'),
        Blob.valueOf('test_key'));
        binaryAttachment.Body = b;
        binaryAttachments[0] =  binaryAttachment ;
        email.binaryAttachments = binaryAttachments ;
        envelope.fromAddress = 'user@fmr.com';

         // Add the email plain text into the local variable       
    Task task = new Task(
       WhatId = (testRequest.Id),
       Description =  email.plainTextBody,
       Priority = 'Normal',
       Status = 'Completed',           
       Type = 'Email',
       Subject = (testRequest.Name),
       ActivityDate = System.today(),
       RecordTypeId = '01250000000HkEw');
    insert task;



        // setup controller object
    RequestEmailHandler catcher = new RequestEmailHandler();
    Messaging.InboundEmailResult result = catcher.handleInboundEmail(email, envelope);
    System.assertEquals( true,result.success );    


    }
}

2 个答案:

答案 0 :(得分:0)

第一步是确定测试类没有涵盖哪些代码行。

如果你正在使用Eclipse,你可以从Apex Test Runner View中看到这一点。

或者,您也可以从Developer Console中看到这一点。

您需要考虑的另一件事是在单独的实用程序类中隔离DML操作。

public class TestUtils
{
   // create request objects method here

   // create task objects method here
}

另外,检查调试日志并确保您的代码没有抛出任何异常(即空指针异常,DML异常等)。

您还必须添加断言以检查您的代码是否按预期运行。

希望这有帮助。

答案 1 :(得分:0)

您需要做的主要事情是通过单元测试尽可能多地测试用例。 因此,设置特定案例的数据并运行您的电子邮件处理。发送电子邮件后,使用System.assertEquals()检查结果。对每个用例进行单独测试。 然后,如果您没有达到至少75%,请检查未涵盖的内容。您可能要么不需要该代码(如果您涵盖所有用例),要么不编写使用这些代码行的用例测试。

相关问题