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
Aiden ByrneAiden Byrne 

Unable to reproduce record locking in Apex Test Method

I'm trying to write a test method where I can simulate record locking so I have validate my exception handling code.

 

Just to make sure that I can demonstrate record locking in a test, I wrote the following very simple test case that creates two users, has the first user lock a record, and has the second user try to update this while the record is still locked. I was expecting an exception, but the test actually succeeds. I would have thought that record locking is per user. Any suggestions?

 

 

   public static testMethod void TestRecordLocks() 
   { 
         Profile p = [SELECT Id FROM profile WHERE name='Standard User']; 
         User u1 = new User(alias = 'zaxxy1', email='zaxxy1@zaxxy1.com', 
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, 
            timezonesidkey='America/Los_Angeles', username='zaxxy1@zaxxy1.com');
         User u2 = new User(alias = 'zaxxy2', email='zaxxy2@zaxxy2.com', 
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, 
            timezonesidkey='America/Los_Angeles', username='zaxxy2@zaxxy2.com');
         //Lets create an account
         Account addAccount = new Account(name='ASFSDFDSAFXXX');
         insert addAccount;
    
         System.runAs(u2) 
         {
         }
         
         System.runAs(u1) 
         {
            Account user1Account = [select id, name from account where name='ASFSDFDSAFXXX' for update ];
        
            System.runAs(u2) 
            {
                Account user2Account = [select id, name from account where name='ASFSDFDSAFXXX' ];
                user2Account.Name = 'test';
//I'd expect that the following update to throw an exception due to the u1 lock, but it actually succeeds
                update user2Account;
           }
            
           user1Account.Name = 'anothertest';
           update user1Account;
        }
   }