0

I created a before delete trigger on Email Message. Everything seems to work fine but when I run the test class, the code coverage is still 0. Do I overlooked something or is something wrong with the test class?

Trigger

trigger EmailMessage_Trigger on EmailMessage (before delete) {    
    If(Trigger.IsBefore){
         MY_EmailMessageTriggerHandler deleteEmail = new MY_EmailMessageTriggerHandler();
        deleteEmail.emailDel(Trigger.old);
    }
}

Trigger handler snippet

  for(EmailMessage EmMes : emailList){
             if(UserInfo.getProfileId() != sysAdId){

                EmMes.addError('You are not allowed to Delete Emails');
             }
        }

Test Class

    @isTest(SeeAllData = TRUE)
private class ALI_EmailMessageTest {

    Static testMethod void CustEmail_test(){

        String uniqueUserName = 'standarduser' + DateTime.now().getTime() + '@testorg.com';
        // This code runs as the system user
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        User u = new User(Alias = 'sysadmin', Email='sysadmin@testorg.com',
        EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
        LocaleSidKey='en_US', ProfileId = p.Id,
        TimeZoneSidKey='America/Los_Angeles',
         UserName=uniqueUserName);

        System.runAs(u) {
              // The following code runs as user 'u'
              System.debug('Current User: ' + UserInfo.getUserName());
              System.debug('Current Profile: ' + UserInfo.getProfileId());
          }


        List<EmailMessage> InsertEmail = new List<EmailMessage>();
        EmailMessage newEmail = new EmailMessage();
        newEmail.Subject = 'TEST';
        newEmail.FromAddress = 'test@abc.org';
        newEmail.Incoming = True;
        newEmail.ToAddress= 'hello@670ocglw7xhomi4oyr5yw2zvf.8kp7yeag.8.case.salesforce.com'; 
        newEmail.Subject = 'Test email';
        newEmail.TextBody = '23456';

        InsertEmail.add(newEmail);

            Delete newEmail;

}
  • Well you never insert it so the delete throws an error which is caught into a black hole. Never use try catch on a test unless you are testing for an error and always throw a failure asset in the try block in case the error does not happen. In your case it did but there is nothing in your catch to show you it was caught or that it happened – Eric Jan 10 '18 at 7:42
  • @Eric Probably should have been an answer... unless you're writing one now? – sfdcfox Jan 10 '18 at 7:45
2

Do not use try-catch unless you're actually expecting an exception, and especially avoid the use of the generic Exception class when you are expecting an exception. This applies in both regular code and unit test code.

Generally, there's a perfectly valid way to rewrite this test to make certain that it behaves as you expect, without catching an exception (thus allowing it to fail if there is an exception).

Database.DeleteResult dr = Database.delete(newEmail, false);
System.assertEquals(false, dr.isSuccess(), 'Expected to fail deletion');
System.assertEquals(StatusCode.FIELD_CUSTOM_VALIDATION_EXCEPTION, sr.getErrors()[0].getStatusCode(), 'Expected a custom validation error');
System.assert(dr.getErrors()[0].getMessage()
    .contains('You are not allowed to Delete Emails', 
    'Expected a "not allowed to delete email" error');

Notice how we avoid the use of try-catch, verify that the status code and message are correct, and that the record was not deleted.

Now, of course, when you run your unit test, you'll get a test failure, and a helpful error message:

System.ListException: Missing id at index: 0

Simply, you forgot to actually insert the record, and therefore it cannot be deleted.

With a few exeptions (no pun intended), you should avoid using try-catch blocks in your code, and instead write code in a way that avoids catching Exception. Unit tests especially should never be trying to catch Exception, but always a specific type of exception, and only if the exception is expected.

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.