0

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;

        Test.StartTest(); 
        system.runAs(u){
            l.Status = 'status_b';
            update l;             
        }
        Test.StopTest(); 

        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 Cook Jul 19 '16 at 14:41
  • What does your before update look like? are you .addError? – EricSSH Jul 19 '16 at 16:45
  • @NickCook has it right. – notthehoff Jul 19 '16 at 17:24
0

via @Nick Cook:

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

| improve this answer | |
0

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='standarduser@testorg.com', 
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
      LocaleSidKey='en_US', ProfileId = p.Id, 
      TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');

      System.runAs(u) {
         // The following code runs as user 'u' 
         System.debug('Current User: ' + UserInfo.getUserName());
         System.debug('Current Profile: ' + UserInfo.getProfileId()); 
      }
| improve this answer | |
  • He is asking about the assert part of it – EricSSH Jul 19 '16 at 17:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.