Use Case:
Mixed DML Error example –
Pre-requisite: Create a Public Group with API name ‘All_Users’. Create a Chatter Group (CollaborationGroup) with name ‘Users‘.
Whenever a new user is inserted,
- Add the user as a member in the above public group.
- Add the User to the above Chatter Group and post about the new user (something like ‘Congratulations UserName’) in the group.
Hint: Here, we would be creating 1 setup object record (public group member of the public group All_Users) and 1 non-setup object record (Feed Item for Chatter Group Users), so use of future method is recommended.
trigger UserTrigger on User (after insert) {if(Trigger.isAfter && Trigger.isInsert) {UserTriggerHandler users = new UserTriggerHandler();// Add the user/users to the public group 'All Users'users.assignToPublicGroup(Trigger.new);// Post about joining of the new user/users in the Chatter Group 'Users'UserTriggerHandler.postToChatterGroup(Trigger.newMap.keySet());}}// Since data for Users Chatter Group would not be visible in the test class and to avoid using seeAllData being true// we would create a new Chatter group and pass the set the new value to 'UserTriggerHandler.chatterGroupName' variablepublic class UserTriggerHandler {@testVisible static String chatterGroupName = 'Users';public void assignToPublicGroup(List<User> newUsers) {// Get the Id of the Public GroupGroup allUsersGroup = [Select Id From Group Where DeveloperName = 'All_Users'];List<GroupMember> groupMembers = new List<GroupMember>();for(User newUser : newUsers) {groupMembers.add(new GroupMember(GroupId = allUsersGroup.Id,UserOrGroupId = newUser.Id));}insert groupMembers;}@futurepublic static void postToChatterGroup(Set<Id> newUsersId) {// Get list of new users insertedList<User> newUsers = [Select Id, Name From User Where Id IN :newUsersId];// Get the Id of the Chatter GroupCollaborationGroup usersChatterGroup = [Select Id From CollaborationGroup Where Name = :chatterGroupName LIMIT 1];List<CollaborationGroupMember> chatterMembers = new List<CollaborationGroupMember>();List<FeedItem> posts = new List<FeedItem>();for(User newUser : newUsers) {chatterMembers.add(new CollaborationGroupMember(CollaborationGroupId = usersChatterGroup.Id,MemberId = newUser.Id));posts.add(new FeedItem(Title = 'Welcome ' + newUser.Name,Body = 'Congratulations to ' + newUser.Name + ' for joining us.',ParentId = usersChatterGroup.Id));}insert chatterMembers;insert posts;}}
Test Class:
Scenario 1- Verify that when a new user is inserted, it should be added to the public group
Scenario 2- Verify that when a new user is inserted, it should be added to the chatter group and a feed should be created
@isTestpublic class TestUserUtil {public static User createUser(String fName, String lName, String alias, Profile profile) {User usr = new User(LastName = lName,FirstName = fName,Alias = alias,Email = fName + '.' + lName + '@apexstepbystep.com',Username = 'test.user444@apexstepbystep.com',ProfileId = profile.id,TimeZoneSidKey = 'GMT',LanguageLocaleKey = 'en_US',EmailEncodingKey = 'UTF-8',LocaleSidKey = 'en_US');return usr;}}@isTestprivate class UserTriggerTest {@testSetupstatic void dataSetup() {CollaborationGroup usersChatterGroup = new CollaborationGroup(Name = 'UsersGroup',CollaborationType = 'Public',OwnerId = UserInfo.getUserId());insert usersChatterGroup;}// Verify that when a new user is inserted, it should be added to the public group@isTeststatic void test_assignToPublicGroup() {UserTriggerHandler.chatterGroupName = 'UsersGroup';// Get the total members of the group 'All_Users' before insertion of new userGroup allUsersGroup = [Select Id From Group Where DeveloperName = 'All_Users'];List<GroupMember> groupMembers = [Select Id From GroupMember Where GroupId = :allUsersGroup.Id];Profile standProfile = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];User newUser = TestUserUtil.createUser('Test', 'User1221', 'tusr', standProfile);Test.startTest();insert newUser;Test.stopTest();// Verify that after the insertion, user should become the member of the public group 'All_Users'// also, created user should be that memberList<GroupMember> newGroupMembers = [Select Id, UserOrGroupId From GroupMember Where GroupId = :allUsersGroup.Id];System.assertEquals(groupMembers.size() + 1, newGroupMembers.size(), 'User is not inserted.');Set<Id> setOfUsersId = new Set<Id>();for(GroupMember member : newGroupMembers) {setOfUsersId.add(member.UserOrGroupId);}System.assert(setOfUsersId.contains(newUser.Id), 'Inserted user should be the group member.');}// Verify that when a new user is inserted, it should be added to the chatter group and a feed should be created@isTeststatic void test_postToChatterGroup() {UserTriggerHandler.chatterGroupName = 'UsersGroup';Profile standProfile = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];User newUser = TestUserUtil.createUser('Test', 'User1221', 'tusr', standProfile);Test.startTest();insert newUser;Test.stopTest();// Verify that after the insertion new User should become a member of Collabration/Chatter GroupCollaborationGroup chatterGroup = [Select Id From CollaborationGroup Where Name = 'UsersGroup' LIMIT 1];List<CollaborationGroupMember> membersAfterInsertion = [Select Id, MemberId From CollaborationGroupMemberWhere CollaborationGroupId = :chatterGroup.Id];Set<Id> setOfUsersId = new Set<Id>();for(CollaborationGroupMember member : membersAfterInsertion) {setOfUsersId.add(member.MemberId);}System.assert(setOfUsersId.contains(newUser.Id), 'Inserted user should be the group member.');// Verify that there should be a feed item which contains the name of the userList<FeedItem> feeds = [Select Id, Body From FeedItem Where ParentId = :chatterGroup.Id];System.assert(feeds[0].Body.contains(newUser.LastName), 'Feed Item was not created.');System.assert(feeds[0].Body.contains(newUser.FirstName), 'Feed Item was not created.');}}
Code Coverage: 100%