I thought I would be able to take a
User
who does not havedelete
privileges on an object, delete records from that object, and get aDmlException
. No dice. Below are theCase
permissions for theStandard User
profile: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
whoseProfile
does not havedelete
permission manage to delete a record? Shouldn’t this throw aDmlException
?
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