0

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

这在沙盒中非常有效,但我没有编写测试类的经验。谁能建议我如何为以下内容编写测试类?

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 );    


    }
}
4

2 回答 2

0

第一步是确定哪些代码行没有被您的测试类覆盖。

如果您使用的是 Eclipse,则可以从 Apex 测试运行器视图中看到这一点。

或者,您也可以从开发人员控制台中看到这一点。

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

public class TestUtils
{
   // create request objects method here

   // create task objects method here
}

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

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

希望这可以帮助。

于 2015-03-16T16:53:52.657 回答
0

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

于 2015-03-17T05:17:44.123 回答