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
slaneslane 

Not able to get System.runAs to work correctly

Hello all:

I am writing a test method that exercises code that duplicates a parent object and its related children. I'm trying to exercise the part of the code that traps for errors inserting the new records. Here's the code I want to exercise
Code:
Savepoint sp = Database.setSavepoint();
  Database.SaveResult sr = Database.Insert (a, false);
        String err;
        
        String newRebateID = sr.getID();
        if ( !sr.isSuccess() ) {
         Database.rollback(sp);
         err = 'Failed to duplicate Rebate: '+this.rebateToClone.id;
         System.debug(err);
         Throw new SMART_Exception(err);
        }

 My strategy was simply to use System.runAs to run as user with insufficient permissions to insert these records. I create a new user on the fly with the appropriate profile, use System.runAs to "become" that user, and run the duplicate routine, all from my test class. I'd expect this to cause the Database.Insert command to return a null set, in which case I should see an exception, which should be caught and managed by this test code:
Code:
system.runas( paragoUser ) {
      Exception theException = null;
      try {
       clonedRebateId = duplicator.dupRebate(); 
      }
      catch ( Exception e ) {
       theException = e;
      }
      // these will throw NPE if the dupe succeeds, which it should not to pass test
      System.assertEquals( theException.getTypeName(), 'SMART_Exception' );
      System.assertEquals( theException.getMessage(), 'Failed to duplicate Rebate: '+ theReb.Id );
     }

 But no exception is thrown. To all appearances, the insert succeeds. I have verified that the relevant profile does not have create privs on either object. I'm using the "with sharing" keyword on both the test class and the class being tested.

Any ideas as to why the active profile doesn't seem to prevent my test from creating records?

Thanks,

Steve Lane

Best Answer chosen by Admin (Salesforce Developers) 
tmatthiesentmatthiesen
RunAs() does not current support CRUD or FLS.  This feature request is on the roadmap.

All Answers

tmatthiesentmatthiesen
RunAs() does not current support CRUD or FLS.  This feature request is on the roadmap.
This was selected as the best answer
slaneslane
Okay -- I thought I remembered something to this effect, but then the documentation shows an example where a system administrator can see (can read, = "R" :->) a record, and a user with lower privs cannot see the record (query returns null set). So I thought I had misunderstood what I heard. Too bad.

Thanks,

Steve