1

Someone on the forum was gracious enough to help me with the below code. Basically, it checks if a case is closed and there is incoming email, it will then clone the case.

Problem is how can I replicate an incoming message in a test class to test the trigger. I can create the new case and change its status to closed with the close, but would be the best way to replicate a new incoming email in the code. Is there an incoming email flag.

Thanks in advance.

trigger AutoCloneCase on EmailMessage (after insert) {
Set<ID> caseSet = new Set<ID>();
List<Case>cloneList = new List<Case>();
for (EmailMessage so : Trigger.new) {
    if(((String)so.parentid).startsWith('500') && so.Incoming){
        caseSet.add(so.parentid); 
    } 
}
Map<Id,case> caseMAP = new Map<Id,case>([SELECT id, isClosed, Type, Auto_Closed__c FROM Case WHERE id in:caseSet]);  
for(Case c:caseMAP.values()){
    if(c.IsClosed && c.Type == 'Support' && c.Auto_Closed__c == true) {
        Case cloneCase = c.clone(false,true);
        cloneCase.parentid=c.id;  
        cloneList.add(cloneCase);
    }
}
try { 
    insert cloneList;      
} catch(DMLException e) {   
     System.debug('The following exception has occurred: ' + e.getMessage()); 
}
}

Then for the test.

@isTest(seeAllData=true)
private class TestSupportTrigger{
static testMethod void myUnitTest() {      
    Case c = new Case(Severity__c = '4 (General Support)',  Origin = 'Self Service   Portal', Subject = 'Unit Test', Type = 'Support', Status = 'Closed', Time_Spent__c = 5, Auto_Closed__C = true );
    insert c;

    EmailMessage[] newEmail = new EmailMessage[0];
    newEmail.add(new EmailMessage(FromAddress = '[email protected]', Incoming = True, ToAddress= '[email protected]', Subject = 'Test email', TextBody = 'Test', ParentId = c.Id)); 

    Test.startTest();     
    insert newEmail;
    Test.stopTest();         
}
}

1 Answer 1

3

Create an EmailMessage in your test case and insert it. Your trigger will fire.

E.g.

static testMethod void lmgtfy() {

    // TODO: Create and Insert a test Case here with isClosed = true and Type = 'Support'
    Case c = //...

    EmailMessage em = new EmailMessage();
    em.FromAddress = '[email protected]';
    em.Incomming = true;
    em.ToAddress = '[email protected]';
    em.Subject = 'Test email';
    em.TextBody = 'Hello';
    em.ParentId = c.Id; // The inserted test Case Id that you created above

    Test.startTest();
    insert em;
    Test.stopTest();

    // TODO: Make assertions that the new cloned cases have been created.

}
1
  • Great. If you consider this a valid answer to your question the convention is to use the green tick to mark it as such. It helps other users find the accepted answer. Commented Mar 4, 2014 at 22:09

You must log in to answer this question.

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