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
Febe NagyFebe Nagy 

Error with Test Class testing account owner changed

Hi,

Can someone help, I keep hitting the same error, insert failed. DML operation on setup object is not permitted after you have updated a non-setup object(or vice versa: User, original object: Account:[].  I am trying to test that the account owner is the same, that the account owner is not the same anymore, so the account owner has changed. Help please.  This is my test class:

@isTest
private class testAccOwner {
    public static testMethod void testAccOwnerChange() 
    {
    test.startTest();
        
	Account acc = new Account(Name = 'test01', OwnerId = 'xxxxxxx001');

    insert acc;
      
        User testUser2 = [Select Id from User where IsActive = true limit 1];
        User testUser3 = [Select Id from User where IsActive = true limit 1];
         
    
    	User testUser1 = new User(alias = 'TstUsr1',Firstname='tst1', email='newuserDP@testorg.com', emailencodingkey='UTF-8', lastname='Tst11', languagelocalekey='en_US', localesidkey='en_US', profileid = 'xxxxxxx006', timezonesidkey='America/Los_Angeles', username='newuser11@testorg.com', UserRoleId = 'xxxxxxx006',Country_picklist__c = 'UNITED STATES',
        Global_Region__c  = 'US', DIRECTOR_NM__c=testUser2.id, ManagerId = testUser3.Id);
        insert testUser1;
        
        System.runAs(testUser1){
        
        acc.OwnerId = testUser1.Id;
        acc.OwnerId = 'xxxxxxx001';
        acc.Previous_Account_Owner__c = 'xxxxxxx001';
        acc.Previous_Account_Owner_s_Manager__c = testUser1.ManagerId;
        acc.New_Account_Owner_s_Manager__c = testUser2.ManagerId;
        acc.OwnerId = testUser2.Id;
        }
        update acc;
        /*System.runAs(u){
			Account acc1 = new Account();
            acc1.OwnerId = 'xxxxxxx001';
            acc1.Name = 'Test091';
            insert acc1;
            
            acc= [select id, ownerId from Account where id=:acc.id];
            system.assert(acc1.OwnerId == acc.OwnerId);
        }*/
        test.stopTest();
    }
}
Best Answer chosen by Febe Nagy
BalajiRanganathanBalajiRanganathan
You should move the insert and update of account dml statements to system.runas block
System.runAs(testUser1){
     
   Account acc = new Account(Name = 'test01', OwnerId = 'xxxxxxx001'); 
   insert acc;
   
        acc.OwnerId = testUser1.Id;
        acc.OwnerId = 'xxxxxxx001';
        acc.Previous_Account_Owner__c = 'xxxxxxx001';
        acc.Previous_Account_Owner_s_Manager__c = testUser1.ManagerId;
        acc.New_Account_Owner_s_Manager__c = testUser2.ManagerId;
        acc.OwnerId = testUser2.Id;
       update acc;
  }