function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Want test to fail insert of custom object

My Salesforce profile called 'Sales'  has no CRUD access to a custom object called Global_Opportunity__c.  But when I run the following test code:


2 private class TestGlobalOpportunityTrigger {

3     static testMethod void salesPersonCantCreateGlobalOpportunity() {

4         User salesUser = [SELECT id FROM User where Profile.Name = 'Sales' AND IsActive=true LIMIT 1];

5         Global_Opportunity__c go = new Global_Opportunity__c(Amount__c = 120000);
6         try {
7           System.runAs(salesUser) {
8           insert go;
9           System.assert(false, 'Sales user was unexpectedly able to create Global_Opportunity id=' + go.Id);

10       }
11    }
12   catch(DmlException excep) {
13       System.debug('got expected excep: ' + excep.getMessage());
14    }

15  }

16 }


Instead of failing the insert as expected and exeecuting line 13, the system executes line 9.

I tried setting the sharing mode to Public Read-only access but this did not solve the problem.

Any ideas?



David Wright



From the Apex Developer Guide ( ):


"Generally, all Apex code runs in system mode, and the permissions and record sharing of the current user are not taken into account. The system method runAs enables you to write test methods that change either the user contexts to an existing user or a new user, or to run using the code from a specific version of a managed package. When running as a user, all of that user's record sharing is then enforced."


Hope this helps..


Hi there TheDoctor,


   Sorry but that doesn't explain the problem.   When using RunAs I would expect the permissions (or lack thereof) of the user to be enforced.  The user profile does not have Create permission on that type of custom object, so I would expect RunAs (user-in-that-profile) should fail when it tries to insert a new record of that type, but it does not.


David Wright