I have a trigger that is working just fine when it is used in production. It's purpose is to grab any attachments before they are inserted and reparent them to the email's parent object if they are an attachment to an email. This works with email to case to attach the files directly to the case instead of the attachment.

My problem is, I'm trying to write a test class that does an assertion and it fails. The assertion says the parent ID is still the email message and not the case. When I actually send a message using email to case, the attachment is reparented just fine.

Is there some known issue in play here? Is there a way for me to assert that the attachment has in fact been reparented?

trigger emailAttachmentReassigner on Attachment (before insert) {
    List<Id> parentIds = new List<Id> {};
    for (Attachment a :trigger.new) {
        if (a.ParentId !=null && a.ParentId.getSObjectType() == EmailMessage.sObjectType) {

    Map<Id, EmailMessage> messageMap = new Map<Id, EmailMessage> ([SELECT Id, ParentId FROM EmailMessage where Id = :parentIds]);

    for( Attachment a : trigger.new ) {
        EmailMessage msg = messageMap.get(a.ParentId);
        if (msg != null) {
            a.ParentId = msg.ParentId;  

Test class:

public class emailAttachmentReassignerTest {
    static testmethod void attachmentTester() {

        Case testCase = (Case) TestUtility.createSObject(new Case());
        insert testCase;

        EmailMessage msg = new EmailMessage(
            ToAddress = 'them.' + Datetime.now().format('yyyymmddhhmmss') + '@sforce.com',
            FromAddress = 'me.' + Datetime.now().format('yyyymmddhhmmss') + '@sforce.com',
            FromName = 'Thomas Train',
            TextBody = 'This is a test of the email attachment reassigner service',
            ParentId = testCase.Id);

        insert msg;

        Attachment a = new Attachment();
        a.name = 'test attachment';
        a.body = blob.valueof('attachment body');
        a.parentid = msg.Id;

        insert a;   

        Attachment testAtt = [SELECT ParentId from Attachment where Id = :a.Id];
        System.assertEquals(testCase.Id, a.ParentId); 


1 Answer 1


You meant:

System.assertEquals(testCase.Id, testAtt.ParentId);

The variable a is the attachment stored in memory, while testAtt is a copy of the record after having been processed by the trigger. The trigger modifies the data send to the database, but doesn't affect any copies of the record that reside in memory elsewhere (in other words, memory references are not "live" references).

  • Gah! I can't tell you how many times I stared at that code. I even requeried it on the line above to get the new values. May 16, 2014 at 3:15
  • Sometimes you just need a fresh pair of eyes.
    – sfdcfox
    May 16, 2014 at 3:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .