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='noemail@noemail.com', 
        timezonesidkey='America/Los_Angeles', 
        localesidkey='en_US', 
        emailencodingkey='UTF-8', 
        ProfileId = p.Id,
        languagelocalekey='en_US', 
        lastname='Testing', 
        Firstname='Testing', 
        CompanyName= 'xyz', 
        username='dim71@noemail.com');
    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.: []

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
}
  • 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 '17 at 16:51
  • That is the expected behavior...it should be caught. What line is throwing that error? – Adrian Larson Jul 21 '17 at 17:08
  • The line in the code is 34 – sfdev Jul 21 '17 at 17:21

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.