11

I thought I would be able to take a User who does not have delete privileges on an object, delete records from that object, and get a DmlException. No dice. Below are the Case permissions for the Standard User profile:

Read,Create,Edit

However the following test fails:

static testMethod void testDmlException_Delete()
{
    List<Case> records = SObjectFactory.create(Case.sObjectType, RECORD_COUNT);
    User standardUser = new User(ProfileId = STANDARD_USER_PROFILE.Id);
    DmlException expectedException;
    system.runAs(standardUser)
    {
        try
        {
            delete records;
        }
        catch (DmlException dmx)
        {
            expectedException = dmx;
        }
    }
    //system.assertEquals(RECORD_COUNT, [SELECT count() FROM Case]);
    //system.assertNotEquals(null, expectedException);
}

Both of the above assertions fail when uncommented. How can a User whose Profile does not have delete permission manage to delete a record? Shouldn't this throw a DmlException?

0

1 Answer 1

11

From the docs:

The runAs method doesn’t enforce user permissions or field-level permissions, only record sharing.

Apex code runs in system context so even though the user does not have delete permissions since the delete is done via apex it is allowed.

You could instead delete the records twice, and the second deletion will cause an error:

static testMethod void testDmlException_Delete()
{
    List<Case> records = SObjectFactory.create(Case.sObjectType, RECORD_COUNT);
    delete records;

    DmlException expectedException;
    Test.startTest();
        try { delete records; }
        catch (DmlException dmx) { expectedException = dmx; }
    Test.stopTest();

    system.assertEquals(RECORD_COUNT, [SELECT count() FROM Case]);
    system.assertNotEquals(null, expectedException);
}
7
  • That is helpful for answering why my methodology does not work, but does leave unresolved the question of how to throw such an exception.
    – Adrian Larson
    Commented Dec 1, 2015 at 18:01
  • 3
    You could cause it buy using a flag to let the method know to delete the record and then attempt to delete it again? Not pretty but works. Sure Crop or sfdcfox will have a better solution
    – Eric
    Commented Dec 1, 2015 at 18:12
  • 5
    I had a feeling I'd come up in this conversation.
    – sfdcfox
    Commented Dec 1, 2015 at 18:45
  • 1
    @AdrianLarson I'd go with a double-delete myself. I just tested this, and it seems to be the only way to do it.
    – sfdcfox
    Commented Dec 1, 2015 at 18:48
  • 2
    Yep double delete does cause the exception I was looking for. @Eric, if you add that to your answer, I will accept it.
    – Adrian Larson
    Commented Dec 1, 2015 at 18:53

You must log in to answer this question.

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