title: How do I write a test class for Messaging.SingleEmailMessage apex class?
body: <p>I have written the below Apex class that processes incoming email that are sent to an email service address and creates a new task from the incoming mail and then associates this new task with a matching record in salesforce. The match is done on the record name and incoming email subject. The class also sends an email notifying the "Assigned to" user that they have received a reply on a request they are working on.</p>
  
  <p>This works perfect in Sandbox but I have no experience writing test classes. Can anyone advise how I write the test class for the below?</p>
  
  <pre><code>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 &amp;&amp; subject.trim().length() &gt; 0 &amp;&amp; subject.indexOf('(R-') &gt; 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&lt;String&gt; toAddresses = new List&lt;String&gt;();
      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;
  }
  </code></pre>
  
  <p>}</p>
  
  <p>Below is my attempt which is only getting 24% coverage. I know it is missing vital code but I do not know enough about test classes to take it any further.</p>
  
  <p>Can anyone assist?</p>
  
  <p>Test Class</p>
  
  <pre><code>@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 );    
  
  
      }
  }
  </code></pre>