I added a new method on a trigger that before update on a lead, checks to see if the user is of a specific profile. If they are, it renders an error. It works fine, but how can I write a unit test for this?

@isTest static void testChangingLeadStatus(){
        Profile profItem = [Select ID, Name
                   From Profile
                   Where Name = 'X Profile'];

        User u = CreateThisUser(profItem);
        insert u;

        Lead l = new Lead();
        l.LastName = 'Test Last';
        l.Company = 'Test Company';
        l.State = 'CA';
        l.Country = 'United States';
        l.Status = 'status_a';
        insert l;

            l.Status = 'status_b';
            update l;             

        system.assertNotEquals(l.Status, 'status_b');


When I run this currently, it gives a DmlException, that I believe is due to the functional prevention of insert... the intended functionality.

System.DmlException: Update failed. First exception on row 0 with id 00Q7A000003D9WERC; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id:

When I comment out the little bit within the runAs block, it passes, but that doesn't really test anything.

How can I run a unit test to ensure that a user cannot update a field that is prevented via before update trigger?

  • 4
    wrap it in a try/catch block and make sure a DMLexception is thrown.
    – Nick C
    Commented Jul 19, 2016 at 14:41
  • What does your before update look like? are you .addError?
    – EricSSH
    Commented Jul 19, 2016 at 16:45
  • @NickCook has it right.
    – notthehoff
    Commented Jul 19, 2016 at 17:24

2 Answers 2


via @Nick Cook:

wrap it in a try/catch block and make sure a DMLexception is thrown.


You can use the RunAs function here the reference: Salesforce documentation

// 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()); 
  • He is asking about the assert part of it
    – EricSSH
    Commented Jul 19, 2016 at 17:59

You must log in to answer this question.

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