0

Recently I have created a simple Apex trigger that copies a standard field to a custom field before insert.

trigger CopyEmailToAltEmail on Contact (before insert) {
    for(Contact c: Trigger.new){
        c.TargetX_Email__AltEmail__c = c.Email;
    }    
}

I had some trouble to get any code coverage using an assert. It turned out a simple debug() output did the trick while an (arguably more appropriate) assert resulted in 0% code coverage. Why is that?

@isTest
private class CopyEmailToAltEmailTest {

    static testMethod void test_BeforeInsertTrigger() {

        Contact c = new Contact();
        c.FirstName='TestFirst';
        c.LastName='TestLast';
        c.Email='ttest@xyz.edu';    
         // Execute trigger with test data set        
        insert c;

        // Confirm results        
        Contact cTest = [select TargetX_Email__AltEmail__c from Contact where id = :c.id];
        //System.assert.equals(t.TargetX_Email__AltEmail__c, 'ttest@xyz.edu'); // 0% coverage?
        System.debug(cTest.TargetX_Email__AltEmail__c); // 100% coverage?
    }
}
4
  • I tried it again and now the assert also gives me full code coverage. Was this just another hickup? – wp78de Jan 3 '18 at 16:47
  • 3
    I was just going to comment that it looks like you had a typo in your code. It should work as you expect (100% coverage), assuming you changed it to System.assertEquals(cTest...) – sfdcfox Jan 3 '18 at 16:48
  • Does your test fail when you use the assertion instead? – Adrian Larson Jan 3 '18 at 16:51
  • I've undone some code changes and tested again. The test did not fail while the debugger showed an error. I think I know what happened: I had configured the wrong test method. This is why the test did not fail but covered 0% of the code. – wp78de Jan 3 '18 at 16:57
1

The debug/assert wont have any impact on the code coverage. The code is being called when you insert the record. Remove both of those lines and you'll notice you still have the code coverage.

Chances are, the 0% you saw resulted from user error such as not running the right test method or looking at the wrong class in the test window. I've been prone to those mistakes in the past so I always double check.

0

it should be

System.assertequals(cTest.TargetXEmail_AltEmail__c, 'ttest@xyz.edu');

but looking at your code it should be

 //System.assert.equals(t.TargetX_Email__AltEmail__c, 'ttest@xyz.edu');
1
  • Good catch. However, I guess it was correct before since I've just reverted some lines of code but not the variable name. – wp78de Jan 3 '18 at 17:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.