1

I'm getting a Code Coverage Error when I attempt to deploy a trigger of mine in a production org. However, it passes the unit tests in a sandbox org.

Here's the test class:

@isTest
private class UpdateFieldUponEmailTestClass {
    static testMethod void validateupdateFieldUponEmail() {
        EmailMessage e = new EmailMessage(Subject = 'test', HtmlBody = 'test');
        Case c = new Case(Id = e.ParentId, Subject = 'test', timesUpdated__c = 0);
        Decimal timesUpdatedOld = c.timesUpdated__c;
        Decimal timesUpdatedNew = timesUpdatedOld + 1;
        System.assertEquals(timesUpdatedOld + 1, timesUpdatedNew);
    }
}

Here's the trigger:

trigger updateFieldUponEmail on EmailMessage (before insert) {
        Set<ID> caseIDs = new Set<ID>();

        for(EmailMessage msg : trigger.new){
            if(msg.parentID.getsObjectType() == Case.sObjectType)
               caseIDs.add(msg.parentID);
        }

        for(Case c: [SELECT timesUpdated__c FROM Case WHERE Id IN :CaseIDs]){
            c.timesUpdated__c = c.timesUpdated__c == null ? 1 : c.timesUpdated__c +1;
        }
}

Side note: for some reason tests take ages to complete in the Developer Console even though it's barely any code. Not sure why.

1 Answer 1

2

You are not actually inserting anything and thus the trigger never fires. Code in test classes are not "used in memory" you actually have to updated the database just like if it happened outside of the test.

So...

@isTest
private class UpdateFieldUponEmailTestClass {
    static testMethod void validateupdateFieldUponEmail() {
        Case c = new Case(Subject = 'test', timesUpdated__c = 0);
        Insert c;
        EmailMessage e = new EmailMessage(ParentId = c.id, Subject = 'test', HtmlBody = 'test');
        insert e;
        //Get updated record
        c = [Select timesUpdated__c From Case Where ID = :c.id];
        //Per you test you know it should only be one per requirements
        System.assertEquals(1, c.timesUpdated__c);
    }
}

You will have to make sure each object has the appropriate fields in order to insert as well

And while you are at it you might want to add a test class to ensure it works properly when the count field is null

static testMethod void countFieldNull() {
    Case c = new Case(Subject = 'test');
    Insert c;
    EmailMessage e = new EmailMessage(ParentId = c.id, Subject = 'test', HtmlBody = 'test');
    insert e;
    //Get updated record
    c = [Select timesUpdated__c From Case Where ID = :c.id];
    //Per you test you know it should only be one per requirements
    System.assertEquals(1, c.timesUpdated__c);
}

You must log in to answer this question.

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