1

I need to cover AddError() in my test class.

Apex Class:

 public void beforeDelete(SObject so) { 
    Task task = (Task) so; 
    Id sysAdminProfileId = [Select Id From Profile WHERE Name = 'System Administrator'].Id;         
    if(UserInfo.getProfileId() != sysAdminProfileId){             
        Task.addError('You have no permissions to delete tasks.'); 
        return; 
    }       
} 

Test class:

static testMethod void testProfile() {

    Test.startTest();

    Profile p = [select id from profile where name='Management'];
    User u = new User(
        alias = 'ddim', 
        email='[email protected]', 
        timezonesidkey='America/Los_Angeles', 
        localesidkey='en_US', 
        emailencodingkey='UTF-8', 
        ProfileId = p.Id,
        languagelocalekey='en_US', 
        lastname='Testing', 
        Firstname='Testing', 
        CompanyName= 'xyz', 
        username='[email protected]');
    insert u;

    Task testTask = new Task(
        subject = 'Test Task',
        priority = 'In Progress',
        OwnerId = u.id
    );

    insert testTask;

    Test.stopTest();

    // Verify that error is thrown when the attachment is deleted
    Boolean errorThrown = false;
    try {
        delete testTask;
    } catch (Exception e) {
        System.debug(e);
        errorThrown = true;
    }
    System.assert(errorThrown);
}

Can someone tell me what I'm missing in my test class in order to get the following covered by my test?

Task.addError('You have no permissions to delete tasks.'); 

Thanks for your suggestion but I get the following error message:

System.DmlException: Delete failed. First exception on row 0 with id 00T9E000004uzukUAA; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, You have no permissions to delete tasks.: []

1 Answer 1

7

You need to run as a user who is not a System Administrator. You already set one up, now you just need to call system.runAs.

system.runAs(u)
{
    // delete here and it should fail
}
3
  • Thanks for your suggestion but I get the following error message: System.DmlException: Delete failed. First exception on row 0 with id 00T9E000004uzukUAA; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, You have no permissions to delete tasks.: []
    – sfdev
    Jul 21, 2017 at 16:51
  • That is the expected behavior...it should be caught. What line is throwing that error?
    – Adrian Larson
    Jul 21, 2017 at 17:08
  • The line in the code is 34
    – sfdev
    Jul 21, 2017 at 17:21

You must log in to answer this question.

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