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
richardvrichardv 

Testing @future with User trigger

I have the following trigger / @future callout which works terrific in the UI.

==============================================================
trigger afterInactivateUser on User (after update) {
 Set<Id> inactivatedParterUsers = new Set<Id>();

 for(Integer i = 0; i < Trigger.new.size(); i++){
  User oldUser = Trigger.old.get(i);
  User updatedUser = Trigger.new.get(i);
  if(updatedUser.ContactId != null && updatedUser.IsActive == false && oldUser.IsActive == true){
   inactivatedParterUsers.add(updatedUser.id);
  }
 }
 if(!inactivatedParterUsers.isEmpty()){
  PartnerUtils.createInactivateUserPartnerRequest(inactivatedParterUsers);
 }
}
==============================================================
==============================================================
public class PartnerUtils {
 @future
 public static void createInactivateUserPartnerRequest(Set<Id> ids){
  List<User> users = new List<User>([select id, ContactId from User where id in :ids]);
  List<MyCustomObject__c> requestList = new List<MyCustomObject__c>();
  MyCustomObject__c request = null;
  for(User user : users){
   request = new MyCustomObject__c();
   request.Contact__c = user.ContactId;
   requestList.add(request);
  }
  insert requestList;
 }

}
==============================================================

However, the following test throws a MIXED_DML_OPERATION when the @future createInactivateUserPartnerRequest() method tries to insert a non-User object:
==============================================================
@IsTest
private class PartnerUtilsTest {
private static testmethod void testAfterInactivateUserTrigger(){
User user = [select id from user where IsActive = true and ContactId != null limit 1];
user.IsActive = false;
update user;
}
}
==============================================================

Any ideas on a workaround that won't fail?
Best Answer chosen by Admin (Salesforce Developers) 
Mohit MohanMohit Mohan

Instead of Using the Api version 15 choose API version 12.That will work

 

 

All Answers

Mohit MohanMohit Mohan

Instead of Using the Api version 15 choose API version 12.That will work

 

 

This was selected as the best answer
TomSnyderTomSnyder

Thanks Mohit,  That fixed my similar issue with the MIXED_DML_OPERATION thrown for User Trigger on UserRoleId updates.