2

I have trigger to stop users to delete task except if profile is "System Administrator".

Trigger :

trigger TaskTrigger on Task (before delete) {
    if(Trigger.isBefore && Trigger.isDelete){
            TaskTriggerHandler.beforeDelete(trigger.old);
    }
}

Handler Class :

public with sharing class TaskTriggerHandler {

    public static void beforeDelete(List<Task> tasks) {    
        Id profileId = Userinfo.getProfileId();
        profile profileName = [select Name from Profile where id=:profileid];
        for(Task t1 : tasks){
            if(profilename.Name != 'System Administrator'){
                t1.addError('Task cannot be deleted');
            }
        }
    }
}

Test class :

@isTest
public class TaskTriggerTest {

    @isTest
    static void testtaskDeletion(){
        Task newtsk = new Task();
        newtsk.Subject = 'Sample';
        newtsk.Status = 'New';
        insert newtsk;
        Profile p =[Select id from Profile where Name = 'Standard User' Limit 1];
        User usr = new User(Alias = 'kaplan', Email='standarduser@xyz.edu',
                            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
                            LocaleSidKey='en_US', ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles',
                            UserName='standarduser@xyz.edu');
        system.runAs(usr){
                try{
                    delete newtsk;
                }catch(Exception e){
                    system.assert(e.getMessage().contains('Task cannot be deleted'));
                }
        }
    }
}

Test Result :

Assertion Failed

16:21:10:964 VARIABLE_ASSIGNMENT [18]|e|"common.apex.runtime.impl.DmlExecutionException: Delete failed. First exception on row 0 with id 00T1b000006RWbTEAW; first error: INSUFFICIENT_ACCESS_OR_READONLY, insufficient access rights on object id: []"|0x532c2782

If I put system.assert(e.getMessage().contains('INSUFFICIENT_ACCESS_OR_READONLY')); Then assertion pass, but trigger and handler class gets 0% code coverage.

2

You created the task as an administrator, then tried to delete it as a normal, unprivileged user. You need to have that user create the task:

    system.runAs(usr){
        insert newtsk;
        try{
            delete newtsk;
        }catch(Exception e){
            system.assert(e.getMessage().contains('Task cannot be deleted'));
        }
    }
2
  • Dang it, Thank you so much.
    – Watson
    May 28 '19 at 20:33
  • @Eklavya You're welcome! It's an easy mistake to make.
    – sfdcfox
    May 28 '19 at 20:39

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.