2

I've written a trigger that will add users to a public group but can't seem to get my test class to work. I have 100% code coverage but the test keeps failing with the Mixed DML Operation error.

Trigger:

    trigger addintoPublicgroup on User (after insert, after update) {
    AddUser.AddToGroups(trigger.newMap.keySet());
}

Class:

//This class is refrenced in the apex trigger Add to Group in order to add users automatically to public groups.
public class AddUser{

@future
public static void AddToGroups(Set<Id> userIds)
{
 //Get the groups that the user should be added to
Group g=[select Id from Group Where DeveloperName='Coordinators'];
Profile p =[select Id from Profile Where Name = 'Sesaco Coordinator'];

 List<User> users=[Select Id,Name from user Where Id IN :userIds and user.ProfileId=:p.Id];

 List<GroupMember>listGroupMember =new List<GroupMember>();  
 // loop the users that have been created
 for (User user : users){
      GroupMember gm= new GroupMember(); 
      gm.GroupId=g.id;
      gm.UserOrGroupId = user.id;
      listGroupMember.add(gm);   
 } 
 insert listGroupMember;
}
}

Test Class:

@isTest
public class addintoPublicgroup_Test {

    static testMethod void AddToGroups(){

    County__c cty = new County__c();
        cty.Name = 'Whitman';
        cty.State__c = 'WA';
        cty.Planting_Area__c = '1';
        insert cty;

    Account act = new Account();
        act.Name = 'Test Account2';
        act.Account_Status__c = 'Active';
        act.BillingCity = 'Pullman';
        act.BillingState = 'WA';
        act.BillingCountry = 'US';
        act.Description = 'Go Cougs';
        act.County__c = cty.Id;
        insert act;

    Contact con = new Contact();
        con.FirstName = 'Test User';
        con.LastName = 'Number One';
        con.Email = '[email protected]';
        con.AccountId = act.Id;
        insert con;

        Profile p = [Select Id from Profile WHERE Name = 'Sesaco Coordinator'];

        User usr = new User();
        usr.FirstName = 'Test User';
        usr.LastName = 'Number One';
        usr.Email = '[email protected]';
        usr.Username = '[email protected]';
        usr.Alias = 'tester';
        usr.ContactId = con.Id;
        usr.ProfileId = p.Id;
        usr.TimeZoneSidKey    = 'America/Denver';
        usr.LocaleSidKey      = 'en_US';
        usr.EmailEncodingKey  = 'UTF-8';
        usr.LanguageLocaleKey = 'en_US';


        try {
            insert usr;
        } catch (Exception e) {
           System.debug('An error occurred');
        }



    }
}

I believe I need to use a combination of System.RunAs and @future in my test class but am unfamiliar with either of those uses in a test class. Any help is appreciated!

0

2 Answers 2

5

You can use Test.startTest and Test.stopTest appropriately to get rid of this issue .

@isTest
public class addintoPublicgroup_Test {

static testMethod void AddToGroups(){

County__c cty = new County__c();
    cty.Name = 'Whitman';
    cty.State__c = 'WA';
    cty.Planting_Area__c = '1';
    insert cty;

Account act = new Account();
    act.Name = 'Test Account2';
    act.Account_Status__c = 'Active';
    act.BillingCity = 'Pullman';
    act.BillingState = 'WA';
    act.BillingCountry = 'US';
    act.Description = 'Go Cougs';
    act.County__c = cty.Id;
    insert act;

Contact con = new Contact();
    con.FirstName = 'Test User';
    con.LastName = 'Number One';
    con.Email = '[email protected]';
    con.AccountId = act.Id;
    insert con;

    Profile p = [Select Id from Profile WHERE Name = 'Sesaco Coordinator'];

    User usr = new User();
    usr.FirstName = 'Test User';
    usr.LastName = 'Number One';
    usr.Email = '[email protected]';
    usr.Username = '[email protected]';
    usr.Alias = 'tester';
    usr.ContactId = con.Id;
    usr.ProfileId = p.Id;
    usr.TimeZoneSidKey    = 'America/Denver';
    usr.LocaleSidKey      = 'en_US';
    usr.EmailEncodingKey  = 'UTF-8';
    usr.LanguageLocaleKey = 'en_US';

    Test.startTest();

    try {
        insert usr;
    } catch (Exception e) {
       System.debug('An error occurred');
    }

   Test.stopTest();
  }
}

If Test.StartTest() and StopTest dont work ,You can use system.RunAs also

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_testing_tools_runas.htm

From the document of salesforce use the below code as sample to understand RunAS

 @isTest

private class TestRunAs {
   public static testMethod void testRunAs() {
  // Setup test data
  // This code runs as the system user
  Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
  User u = new User(Alias = 'standt', Email='[email protected]', 
  EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
  LocaleSidKey='en_US', ProfileId = p.Id, 
  TimeZoneSidKey='America/Los_Angeles', UserName='[email protected]');

  System.runAs(u) {
     // The following code runs as user 'u' 
     System.debug('Current User: ' + UserInfo.getUserName());
     System.debug('Current Profile: ' + UserInfo.getProfileId()); 
    }
  }
}

Example code of how to use nested system.RunAS

 @isTest

private class TestRunAs2 {

  public static testMethod void test2() { 

  Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
  User u2 = new User(Alias = 'newUser', Email='[email protected]', 
     EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
     LocaleSidKey='en_US', ProfileId = p.Id, 
     TimeZoneSidKey='America/Los_Angeles', UserName='[email protected]');

  System.runAs(u2) {
     // The following code runs as user u2. 
     System.debug('Current User: ' + UserInfo.getUserName());
     System.debug('Current Profile: ' + UserInfo.getProfileId()); 

     // The following code runs as user u3. 
     User u3 = [SELECT Id FROM User WHERE UserName='[email protected]'];
     System.runAs(u3) {
        System.debug('Current User: ' + UserInfo.getUserName());
        System.debug('Current Profile: ' + UserInfo.getProfileId()); 
     }

     // Any additional code here would run as user u2.
     }
  }
}
0
1

Thanks to @Mohith , here's my code that resulted in 100% coverage and a successful deployment:

@isTest
public class addintoPublicgroup_Test {

    static testMethod void AddToGroups(){

    County__c cty = new County__c();
        cty.Name = 'Whitman';
        cty.State__c = 'WA';
        cty.Planting_Area__c = '1';
        insert cty;

    Account act = new Account();
        act.Name = 'Test Account2';
        act.Account_Status__c = 'Active';
        act.BillingCity = 'Pullman';
        act.BillingState = 'WA';
        act.BillingCountry = 'US';
        act.Description = 'Go Cougs';
        act.County__c = cty.Id;
        insert act;

    Group grp = [SELECT Id from Group Where DeveloperName='Coordinators'];

    Contact con = new Contact();
        con.FirstName = 'Test User';
        con.LastName = 'Number One';
        con.Email = '[email protected]';
        con.AccountId = act.Id;
        insert con;

        Profile p = [Select Id from Profile WHERE Name = 'System Administrator'];

        User usr = new User();
        usr.FirstName = 'Test User';
        usr.LastName = 'Number One';
        usr.Email = '[email protected]';
        usr.Username = '[email protected]';
        usr.Alias = 'tester';
        //usr.ContactId = con.Id;
        usr.ProfileId = p.Id;
        usr.TimeZoneSidKey    = 'America/Denver';
        usr.LocaleSidKey      = 'en_US';
        usr.EmailEncodingKey  = 'UTF-8';
        usr.LanguageLocaleKey = 'en_US';
        insert usr;

        System.runAs(usr){

        Profile p1 = [Select Id from Profile Where Name ='Sesaco Coordinator'];

        User usr1 = new User();
        usr1.FirstName = 'Test User';
        usr1.LastName = 'Number Two';
        usr1.Email = '[email protected]';
        usr1.Username = '[email protected]';
        usr1.Alias = 'tester';
        usr1.ContactId = con.Id;
        usr1.ProfileId = p1.Id;
        usr1.TimeZoneSidKey    = 'America/Denver';
        usr1.LocaleSidKey      = 'en_US';
        usr1.EmailEncodingKey  = 'UTF-8';
        usr1.LanguageLocaleKey = 'en_US'; 

        Test.startTest();
        try {
            insert usr1;
        } catch (Exception e) {
           System.debug('An error occurred');
        }
        Test.stopTest();
        }

    }
}

Not the answer you're looking for? Browse other questions tagged .