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
jill.longojill.longo 

Test Class failing with DML exception

Getting a Dml exception error when running a test class.

Error Message System.DmlException: Insert failed. First exception on row 0; 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: []
Stack Trace Class.TaskTriggerTest.getAccount: line 141, column 1
Class.TaskTriggerTest.testTask5: line 116, column 1
 
Also getting a errror at line 9, column 1, line 38, column 1, line 60, column 1, line 88, column 1


Here's the Trigger:

@isTest
private class TaskTriggerTest {
   
    // test the task Count
    static testMethod void testTask() {
       
        Test.startTest();
        User user = UserNewTestData();
        Account ac = getAccount('Test Account');
       
        Program__c prog = getProgram(ac);
        getAccountTeam(prog);
       
        system.debug('Test Class - Program: '+ prog.Id);
       
        Case c = getCase(user.Id, ac,prog);
       
        Map<Id, Task> mapTask = new Map<Id,Task>();
       
        system.debug('Test Class - Case: '+ c.Id);
        system.debug('Test Class - User: '+ user.Id);
        system.debug('Test Class - Case Program: '+ c.Program__c);
       
        mapTask = getTasks(c.Id,user.Id);
        system.debug('Test Class - mapTask = ' + mapTask.size());
       
        CaseAutomation.updateCaseTaskCount(mapTask,'In Progress','Insert');
        Test.stopTest();
    }
   
   
    // test the task Count
    static testMethod void testTask2() {
       
        Test.startTest();
       
        User user = UserNewTestData();
        Account ac = getAccount('Test Account');
       
        Program__c prog = getProgram(ac);
        getAccountTeam(prog);
        Case c = getCase(user.Id, ac,prog);
       
        Map<Id, Task> mapTask = new Map<Id,Task>();
       
        mapTask = getTasks(c.Id,user.Id);
       
        CaseAutomation.updateCaseTaskCount(mapTask,'In Progress','Delete');
        CaseAutomation.rollupTotalTasktime(mapTask);
       
        Test.stopTest();
    }
   
      // test the task Count
    static testMethod void testTask3() {
       
        Test.startTest();
       
        User user = UserNewTestData();
        Account ac = getAccount('Test Account');
       
        Program__c prog = getProgram(ac);
        getAccountTeam(prog);
        Case c = getCase(user.Id, ac,prog);
       
        List<Task> newTask = new List<Task>();
        Map<Id, Task> mapTask = new Map<Id,Task>();
       
        mapTask = getTasks(c.Id,user.Id);
       
        for(Task task : mapTask.values()){
            newTask.add(task);
        }
       
        CaseAutomation.updateCaseTaskCount(mapTask,'Completed','');
        CaseAutomation.sendEmailToTeam(newTask,newTask);
        CaseAutomation.addCaseComment(newTask,'Completed');
        CaseAutomation.rollupTotalTasktime(mapTask);
       
        Test.stopTest();
    }
   
    // test the task Count
    static testMethod void testTask4() {
        Test.startTest();
       
        User user = UserNewTestData();
        Account ac = getAccount('Test Account');
       
        Program__c prog = getProgram(ac);
        getAccountTeam(prog);
        Case c = getCase(user.Id, ac,prog);
       
        List<Task> newTask = new List<Task>();
        Map<Id, Task> mapTask = new Map<Id,Task>();
       
        mapTask = getTasks(c.Id,user.Id);
       
        for(Task task : mapTask.values()){
            newTask.add(task);
        }
       
        CaseAutomation.updateCaseTaskCount(mapTask,'In Progress','');
        CaseAutomation.addCaseComment(newTask,'Completed');
        CaseAutomation.rollupTotalTasktime(mapTask);
       
        Test.stopTest();
    }
   
      // test the task Count
    static testMethod void testTask5() {
       
        Test.startTest();
       
        User user = UserNewTestData();
        Account ac = getAccount('Test Account');
       
        Program__c prog = getProgram(ac);
        getAccountTeam(prog);
        Case c = getCase(user.Id, ac,prog);
       
        List<Task> newTask = new List<Task>();
        Map<Id, Task> mapTask = new Map<Id,Task>();
       
        mapTask = getTasks(c.Id,user.Id);
       
        for(Task task : mapTask.values()){
            newTask.add(task);
        }
       
        delete newTask;
       
       
        Test.stopTest();
    }
   
   
      // get an account for the parameter passed
    static Account getAccount(String accountName) {
        Account ac = new Account(Name = accountName, website='www.hotmail.com',Account_Status__c = 'Prospect',BillingStreet= '1',BillingCity = '1', BillingState = '1', BillingPostalCode = '12345');
        insert ac;
        return ac;     
    }
   
    static Program__c getProgram(Account ac){
        Program__c prog = new Program__c(
            Name = 'Test Program',
            Account__c = ac.Id,
            Platform__c = 'Marin',
            Website__c = 'www.google.com'
        );
       
        insert prog;       
        return prog;
    }
   
    static void getAccountTeam(Program__c prog){
        Account_Team__c acTeam = new Account_Team__c(
            Program__c = prog.Id,
            Date_Assigned__c = Date.parse('2/25/2015'),
            o__c = 'AM'        
        );
       
        insert acTeam;
       
    }
   
     //test data for Case   
    static Case getCase(Id userId, Account ac,Program__c prog){
       
        Case newCase = new Case(
            AccountId = ac.Id,
            Business_Unit__c = 'Paid Search',
            Request__c = 'New Campaign',
            Sub_Request__c = 'New Campaign',
            Assigned_To__c =  userId,
            Due_Date__c = Date.parse('2/25/2015'),
            Total_of_Closed_Task_s__c = 2,
            Total_of_Open_Task_s__c = 2,
            Total_of_Overdue_Task_s__c = 0,
            Program__c = prog.Id
        );
       
        insert newCase;
        return newCase;
    }
   
    static Map<Id,Task> getTasks(Id caseId,Id userId){
       
        List<Task> lstTask = new List<Task>();
        Task task = null;
        Map<Id,Task> mapTask = new Map<Id,Task>();
       
       
        for(Integer counter =0;counter<=5;counter++){
            task = new Task();
           
            task.WhatId = caseId;
            task.Subject = 'Test Task';
           
            if(counter<=3)
                task.Status = 'In Progress';
            else
                task.Status = 'Completed';
               
            task.Priority = 'Normal';
            //task.IsRecurrence = false;
            task.OwnerId = userId;
           
            lstTask.add(task);
        }
       
        insert lstTask;
       
        for(Task newTask: lstTask){
           
            mapTask.put(newTask.Id,newTask);
        }
       
        return mapTask;
    }
   
     static User UserNewTestData(){
        Profile profile = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
               
       
        User usr = new User();
        usr.LastName = 'test user';
        usr.Alias = 'tst';
        usr.Email = 'testuer@domain.com';
        usr.UserName = 'test_xyz1234@test.com' ;
        usr.CommunityNickname = 'tests';
        usr.UserRoleId = userInfo.getUserRoleId();
        usr.TimeZoneSidKey = 'America/Los_Angeles';
        usr.ProfileId = profile.Id ;
        usr.LocaleSidKey = 'en_US' ;
        usr.EmailEncodingKey = 'ISO-8859-1';
        usr.LanguageLocaleKey = 'en_US';      
        usr.isActive = true;
       
        insert usr;
        return usr;
    }

}
Boris BachovskiBoris Bachovski
That error you're getting on line (116 -> 141) means that you cannot perform a DML operation (Insert, update, upsert, delete) on a setup object (User in this case) and then straight after that another DML operation on a non-setup (standard or custom object, Account in this case) object.

In your case you need to move this line
User user = UserNewTestData();
outside `Test.StartTest()` and `Test.StopTest()` methods (just before the `Test.StartTest()` actually).

Here you can read more around this:
http://www.salesforce.com/us/developer/docs/dbcom_apex/Content/apex_dml_non_mix_sobjects_test_methods.htm

Regarding the rest of your errors, can you please provide the error message? It might be a validation rule or something that is preventing the account from being inserted etc.

Good luck!
shiv@SFDCshiv@SFDC
Please use system.runas

your_testMethods
 {
	 User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
	 System.runAs (thisUser) 
	 {
		Test.startTest();
		
		// Other content of your test methods Like
		 User user = UserNewTestData();
		 Account ac = getAccount('Test Account');
	   
		 Program__c prog = getProgram(ac);
		 getAccountTeam(prog);
		 Case c = getCase(user.Id, ac,prog);
	   
		 Map<Id, Task> mapTask = new Map<Id,Task>();
	   
		 mapTask = getTasks(c.Id,user.Id);
	   
		 CaseAutomation.updateCaseTaskCount(mapTask,'In Progress','Delete');
		 CaseAutomation.rollupTotalTasktime(mapTask);
		
		Test.stopTest();
	 }
 }

IF it solves your issue please mark answer as a solution.