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
Siva AdminSiva Admin 

Help in the Test Class

Hi all I'm a newbee to SF, trying to get some hand on Test Classes. Have been trying to write a test class for it, but cannot. 

trigger RecordOwnerChange on user (after update){
if (trigger.isafter & trigger.isupdate){

   List<Id> recordIds = new List<Id>();
   
  List<account> aclst = [select id, ownerid, owner.isActive, owner.Managerid from Account where OwnerId IN:trigger.new];
  for (Account ac: aclst){
   if (ac.owner.isActive == false && ac.owner.managerid != null){
    recordIds.add(ac.id);
    }
  }
 if(!recordIds.isEmpty()){
  RecordOwnerChange_4Handler.updateaccounts(recordIds);
    }

CLASS:
public class RecordOwnerChangeHandler {
@future
 public static void updateaccounts(List<Id> recordIds){
 List<Account> updateacclist = new List<Account>();
 for (Account ac:[select ownerid, owner.Managerid from Account where Id IN:recordIds]){
 ac.ownerid= ac.owner.managerid;
 updateacclist.add(ac);
 }
 if(updateacclist.size()>0){
 update updateacclist ;
}}}

kindly help me on this regards. Thanks.
sathishkumar periyasamysathishkumar periyasamy
@siva, before we go to test class - you can update account record from user trigger. why are you using @future method to update account record?
Siva AdminSiva Admin
Hi Sathiskumar. Thanks for responding.

With normal trigger, getting below error:
"Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger RecordOwnerChange caused an unexpected exception, contact your administrator: RecordOwnerChange: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 0012800000k4GFLAA2; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): Account, original object: User: []: Trigger.RecordOwnerChange: line 18, column 1"

with future method, it's working fine.