0 votes
1 view
by

The permission to delete Accounts is unchecked in test User Profile according to this trailhead article. https://trailhead.salesforce.com/en/content/learn/projects/protect-your-data-in-salesforce/create-new-users-and-delete-accounts enter image description here

I checked manually by logging on behalf the user with the profile. The restriction works - delete button is hidden everywhere. No way to delete accounts.

However, I can still delete account in a unit test.

@isTest
private with sharing class AccountTest {

@isTest
static void testAccountCRUD () {
    User testUser = TestDataFactory.generateUser('Standard Profile - No Acct Delete', 'Western Sales Team');
    insert testUser;

    Account[] testAccountList = new Account[]{};

    // Create
    System.runAs(testUser) {
        Account testAccount = TestDataFactory.generateAccount();
        testAccountList.add(testAccount);
        insert testAccount;
    }

    // Read
    System.runAs(testUser) {
        Account[] accList = [select Id, OwnerId, Name from Account];
        System.assertEquals(1, accList.size());
    }

    // Delete
    System.runAs(testUser) {
        System.assertEquals(true, Database.delete(testAccountList[0], false).isSuccess());
    }
    
    // Read
    System.runAs(testUser) {
        Account[] accList = [select Id, OwnerId, Name from Account];
        System.assertEquals(0, accList.size()); // account was deleted
    }
}
}

Why it is possible to delete accounts in unit tests even if the user doesn't have the permission?

1 Answer

0 votes
by
 
Best answer

The answer is yes, Salesforce doesn't perform object-level permission or field level permission checks in Apex.

In order to do that you need to do something like:

if (Schema.sObjectType.Account.isDeletable()) {
  System.assertEquals(true, Database.delete(testAccountList[0], false).isSuccess());
}

See the documentation about Enforcing Object and Field Permissions.

Another detail worth pointing out is that System.runAs don't respect object or field level permission, being useful for testing sharing rules but not for that (as seen in the docs).

Welcome to Memory Exceeded, where you can ask questions and receive answers from other members of the community.
...