How To Cause DmlException – Delete

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?

Answer

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);
}

Attribution
Source : Link , Question Author : Adrian Larson , Answer Author : Adrian Larson

Leave a Comment