I have some legacy test classes that I'm updating. One of these get's hung-up by a validation rule that requires a record only be changed by certain users/profile.

Now, I understand that test classes are run by the system and not as any particular users - is this correct? If so, can I structure the validation rule to allow system / test class to make the changes?

Thanks in advance!


2 Answers 2


The unit tests run as the user that started the test. You can also use the System.runAs method to run the code as different users. See the example below which creates a new user and then runs the code as that user.

private class TestRunAs {
   public static testMethod void testRunAs() {
      // Setup test data
      // This code runs as the system user
      Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
      User u = new User(Alias = 'standt', Email='[email protected]', 
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
      LocaleSidKey='en_US', ProfileId = p.Id, 
      TimeZoneSidKey='America/Los_Angeles', UserName='[email protected]');

      System.runAs(u) {
         // The following code runs as user 'u' 
         System.debug('Current User: ' + UserInfo.getUserName());
         System.debug('Current Profile: ' + UserInfo.getProfileId()); 

Create a custom setting and add the profile or user for whom this validation rule need to be passed and refer that in the validation rule as condition, so it can fire for other users except those included in custom setting

  • I've read about this as a solution. However, I might as well just add myself as exempt from the validation rule itself. I thing the RunAs might be more permanent in the long-term (unless the validation rule changes). Thanks for your response! Mar 9, 2015 at 21:25
  • We've been contemplating this option for a while now and its good for specific use cases like: (1) Temporary disablement for bulk DML or (2) Temporary disablement for getting past deployments that have failed existing test methods. IMPORTANT: We only update the custom setting to disable only during these or similar use cases and its for a very narrow window of time. We also only enable for the System Administrator profile so as not to impact any business user functionality. Lastly, we never leave enabled! Jan 26, 2017 at 18:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .