Use Case:
NOTE: An extended version of Example 8.
(Example 8: Whenever a new User having profile “System Administrator” is inserted and is Active, add the user to the public group “Admins”.
Pre-requisite: Create a public group with name as “Admins”.)
Write a trigger: to add the user to the public group “Admins”
- If the active user’s profile is updated from anything to System Administrator, the user should be added in the group.
- If the active user’s profile is updated from System Administrator to something else, the user should be removed from the group.
- If the user having System Administrator profile is marked active, should be added to the group.
- If the user having System Administrator profile is marked inactive, should be removed from the group.
trigger UserTrigger on User (after insert, after update) {if(Trigger.isAfter) {if(Trigger.isInsert) {UserTriggerHandler.addAdminToPublicGroup(Trigger.new);}if(Trigger.isUpdate) {UserTriggerHandler.updatePublicGroupUsers(Trigger.new, Trigger.oldMap);}}}public class UserTriggerHandler {private static Group adminGroup = [SELECT Id FROM Group WHERE DeveloperName = 'Admins' AND Type = 'Regular' LIMIT 1];private static Profile adminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];public static void addAdminToPublicGroup(List<User> newUsers) {// Get Id of Public group for Admins//Group adminGroup = [SELECT Id FROM Group WHERE DeveloperName = 'Admins' AND Type = 'Regular' LIMIT 1];// Perform operation of adding Admin users to the group only when Group is present in salesforceif(adminGroup != NULL) {List<GroupMember> groupMembers = new List<GroupMember>();// Get admin proifle and check for all users,// if user profile id is same as the admin profile id AND user is active then only create a new group member//Profile adminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];for(User user : newUsers) {if(user.ProfileId == adminProfile.Id && user.IsActive == true) {groupMembers.add(new GroupMember(GroupId = adminGroup.Id, UserOrGroupId = user.Id));}}insert groupMembers;}}public static void updatePublicGroupUsers(List<User> newUsers, Map<Id,User> oldUsersMap) {if(adminGroup != NULL) {List<GroupMember> newGroupMembers = new List<GroupMember>();List<GroupMember> existingGroupMembers = [SELECT Id, GroupId, UserOrGroupId FROM GroupMember WHERE Group.Id = :adminGroup.Id];List<GroupMember> membersToBeDeleted = new List<GroupMember>();Set<Id> usersAsGroupMembers = new Set<Id>();for(User user : newUsers) {// When profile of an active user is changedif(user.ProfileId != oldUsersMap.get(user.Id).ProfileId && user.IsActive == true) {// If new profile is System Administrator then create a new group member for adminif(user.ProfileId == adminProfile.Id) {newGroupMembers.add(new GroupMember(GroupId = adminGroup.Id, UserOrGroupId = user.Id));}// If new profile is Not System Administrator and old profile was System Administrator then delete the existing group member if presentif(oldUsersMap.get(user.Id).ProfileId == adminProfile.Id) {usersAsGroupMembers.add(user.Id);}}else {// When user with System Administrator profile is marked active or inactiveif(user.IsActive != oldUsersMap.get(user.Id).IsActive && user.ProfileId == adminProfile.Id) {// If user is marked active from inactive then create a new group member for adminif(user.IsActive == true) {newGroupMembers.add(new GroupMember(GroupId = adminGroup.Id, UserOrGroupId = user.Id));}// If user is marked inactive from active, then delete the existing group member if presentif(user.IsActive == false) {usersAsGroupMembers.add(user.Id);}}}}insert newGroupMembers;for(GroupMember member : existingGroupMembers) {if(usersAsGroupMembers.contains(member.UserOrGroupId)) {membersToBeDeleted.add(member);}}delete membersToBeDeleted;}}}
Test Class:
Scenario 1- Verify that when an active user’s profile is changed to System Administrator then GroupMember record is created for the public group Admins.
Scenario 2- Verify that when profile is changed to some profile other than the System Administrator, then GroupMember record is deleted for the public group Admin.
Scenario 3- Verify that when an inactive user with profile System Administrator is made active, then a GroupMember record is created for the public group Admins for the user
Scenario 4- Verify that when an active user with profile System Administrator is made inactive, then a GroupMember record should be deleted for the public group Admins for the user
@isTestpublic class TestUserUtil {public static User createUser(String fName, String lName, String alias, String username, Profile profile) {User usr = new User(LastName = lName,FirstName = fName,Alias = alias,Email = fName + '.' + lName + '@apexstepbystep.com',Username = username,ProfileId = profile.id,TimeZoneSidKey = 'GMT',LanguageLocaleKey = 'en_US',EmailEncodingKey = 'UTF-8',LocaleSidKey = 'en_US');return usr;}}@isTestprivate class UserTriggerTest {// Verify that when user having System Administrator profile is created, the user is also added to the public group Admin.@isTeststatic void testUserInsertion_valid() {Group adminGroup = [SELECT Id FROM Group WHERE DeveloperName = 'Admins' AND Type = 'Regular' LIMIT 1];// GroupMembers before insertionList<GroupMember> membersBefore = [SELECT Id From GroupMember Where GroupId = :adminGroup.Id];Profile adminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];User usr = TestUserUtil.createUser('Test', 'User', 'tusr', 'test.user444@apexstepbystep.com', adminProfile);Test.startTest();insert usr;Test.stopTest();// Assert that members after insertion should be exactly 1 greater than beforeList<GroupMember> membersAfter = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];System.assertEquals(membersBefore.size() + 1, membersAfter.size(), 'User is not added to group Admins.');Set<Id> userIdsSet = new Set<Id>();for(GroupMember member : membersAfter) {userIdsSet.add(member.UserOrGroupId);}System.assertEquals(true, userIdsSet.contains(usr.Id), 'GroupMember should be present for the inserted user.');}// Verify that when user having other than the System Administrator profile is created, the user should not be added to the public group Admin.@isTeststatic void testUserInsertion_invalid() {Group adminGroup = [SELECT Id FROM Group WHERE DeveloperName = 'Admins' AND Type = 'Regular' LIMIT 1];// GroupMembers before insertionList<GroupMember> membersBefore = [SELECT Id From GroupMember Where GroupId = :adminGroup.Id];Profile standardProfile = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];User usr = TestUserUtil.createUser('Test', 'User', 'tusr', 'test.user444@apexstepbystep.com', standardProfile);Test.startTest();insert usr;Test.stopTest();// Assert that members after insertion should be same as beforeList<GroupMember> membersAfter = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];System.assertEquals(membersBefore.size(), membersAfter.size(), 'Group Members count is not same.');Set<Id> userIdsSet = new Set<Id>();for(GroupMember member : membersAfter) {userIdsSet.add(member.UserOrGroupId);}System.assertEquals(false, userIdsSet.contains(usr.Id), 'GroupMember should not be present for the inserted user.');}// Verify that when an active user's profile is changed to System Administrator then GroupMember record is created for the public group Admins@isTeststatic void test_updatePublicGroupUsers_profileAdmin() {Group adminGroup = [SELECT Id FROM Group WHERE DeveloperName = 'Admins' AND Type = 'Regular' LIMIT 1];Profile standardProfile = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];User usr = TestUserUtil.createUser('Test', 'User', 'tusr', 'test.user444@apexstepbystep.com', standardProfile);insert usr;// GroupMembers in the adminGroup before updation. Assert that user should not be a member of the public group.List<GroupMember> membersBefore = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];Set<Id> groupMembersIdsBefore = new Set<Id>();for(GroupMember member : membersBefore) {groupMembersIdsBefore.add(member.UserOrGroupId);}System.assertEquals(false, groupMembersIdsBefore.contains(usr.Id), 'GroupMember should not be present for the inserted user.');// Update profile of the inserted user to System AdministratorProfile adminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];Test.startTest();usr.ProfileId = adminProfile.Id;update usr;Test.stopTest();// Assert that after updating the profile to System Administrator, a new group member for public group Admins should be createdList<GroupMember> membersAfter = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];System.assertEquals(membersBefore.size() + 1, membersAfter.size(), 'Group Members count is same.');Set<Id> userIdsSet = new Set<Id>();for(GroupMember member : membersAfter) {userIdsSet.add(member.UserOrGroupId);}System.assertEquals(true, userIdsSet.contains(usr.Id), 'GroupMember should be present for the inserted user.');}// Verify that when profile is changed to some profile other than the System Administrator, then GroupMember record is deleted for the public group Admin.@isTeststatic void test_updatePublicGroupUsers_profileNotAdmin() {Group adminGroup = [SELECT Id FROM Group WHERE DeveloperName = 'Admins' AND Type = 'Regular' LIMIT 1];Profile adminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];User usr = TestUserUtil.createUser('Test', 'User', 'tusr', 'test.user444@apexstepbystep.com', adminProfile);insert usr;// GroupMembers in the adminGroup before updation. Assert that user should be a member of the public group.List<GroupMember> membersBefore = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];Set<Id> groupMembersIdsBefore = new Set<Id>();for(GroupMember member : membersBefore) {groupMembersIdsBefore.add(member.UserOrGroupId);}System.assertEquals(true, groupMembersIdsBefore.contains(usr.Id), 'GroupMember should be present for the inserted user.');// Update profile of the inserted user to Standard UserProfile standardProfile = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];Test.startTest();usr.ProfileId = standardProfile.Id;update usr;Test.stopTest();// Assert that after updating the profile to Standard User, the group member for public group Admins should be deletedList<GroupMember> membersAfter = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];System.assertEquals(membersBefore.size() - 1, membersAfter.size(), 'Group Members count is same.');Set<Id> userIdsSet = new Set<Id>();for(GroupMember member : membersAfter) {userIdsSet.add(member.UserOrGroupId);}System.assertEquals(false, userIdsSet.contains(usr.Id), 'GroupMember is not deleted for the user.');}// Verify that when an inactive user with profile System Administrator is made active, then a GroupMember record is created for the public group Admins for the user@isTeststatic void test_updatePublicGroupUsers_active() {Group adminGroup = [SELECT Id FROM Group WHERE DeveloperName = 'Admins' AND Type = 'Regular' LIMIT 1];Profile adminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];User usr = TestUserUtil.createUser('Test', 'User', 'tusr', 'test.user444@apexstepbystep.com', adminProfile);usr.IsActive = false;insert usr;// GroupMembers in the adminGroup before updationList<GroupMember> membersBefore = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];Set<Id> groupMembersIdsBefore = new Set<Id>();for(GroupMember member : membersBefore) {groupMembersIdsBefore.add(member.UserOrGroupId);}System.assertEquals(false, groupMembersIdsBefore.contains(usr.Id), 'GroupMember should not be present for the inserted user.');// Make the user active by updating IsActive checkbox trueTest.startTest();usr.IsActive = true;update usr;Test.stopTest();// Assert that the group member for public group Admins should be created for the userList<GroupMember> membersAfter = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];System.assertEquals(membersBefore.size() + 1, membersAfter.size(), 'Group Members count is same.');Set<Id> userIdsSet = new Set<Id>();for(GroupMember member : membersAfter) {userIdsSet.add(member.UserOrGroupId);}System.assertEquals(true, userIdsSet.contains(usr.Id), 'GroupMember should be created for the inserted user.');}// Verify that when an active user with profile System Administrator is made inactive, then a GroupMember record should be deleted for the public group Admins for the user@isTeststatic void test_updatePublicGroupUsers_inActive() {Group adminGroup = [SELECT Id FROM Group WHERE DeveloperName = 'Admins' AND Type = 'Regular' LIMIT 1];Profile adminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];User usr = TestUserUtil.createUser('Test', 'User', 'tusr', 'test.user444@apexstepbystep.com', adminProfile);insert usr;// GroupMembers in the adminGroup before updation.List<GroupMember> membersBefore = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];Set<Id> groupMembersIdsBefore = new Set<Id>();for(GroupMember member : membersBefore) {groupMembersIdsBefore.add(member.UserOrGroupId);}System.assertEquals(true, groupMembersIdsBefore.contains(usr.Id), 'GroupMember should be present for the inserted user.');// Make the user active by updating IsActive checkbox trueTest.startTest();usr.IsActive = false;update usr;Test.stopTest();// Assert that the group member for public group Admins should be deleted for the userList<GroupMember> membersAfter = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];System.assertEquals(membersBefore.size() - 1, membersAfter.size(), 'Group Members count is same.');Set<Id> userIdsSet = new Set<Id>();for(GroupMember member : membersAfter) {userIdsSet.add(member.UserOrGroupId);}System.assertEquals(false, userIdsSet.contains(usr.Id), 'GroupMember should be deleted for the user.');}}
Code Coverage: 100%