Salesforce: Create Test Data for Group and GroupMember Objects in Test Class

Sample Test Class:

@isTest
global class SampleTestClass
{
	public static TestMethod void TestSampleMethod()
	{
		Test.startTest();     

		//Create Parent Group
		Group grp = new Group();
		grp.name = 'Test Group1';
		grp.Type = 'Regular'; 
		Insert grp; 

		//Create Group Member
		GroupMember grpMem1 = new GroupMember();
		grpMem1.UserOrGroupId = UserInfo.getUserId();
		grpMem1.GroupId = grp.Id;
		Insert grpMem1;

		//Create Sub group
		Group subGrp  = new Group();
		subGrp.name = 'Test Group2';
		subGrp.Type = 'Regular'; 
		Insert subGrp; 

		//Assign Role To Parent Group
		GroupMember grpMem2 = new GroupMember();
		grpMem2.UserOrGroupId = subGrp.Id;
		grpMem2.GroupId = grp.Id;
		Insert grpMem2;  

		//Create Group Map Data
		Map<String,Id> groupNameRoleIdMap = new Map<String,Id>();
		for(Group gp: [SELECT Id, Name FROM Group WHERE Type = 'Role']){
			groupNameRoleIdMap.put('SuperAdmin', gp.Id);
		}     

		//Assign role to parent group
		GroupMember grpMem3 = new GroupMember();
		grpMem3.UserOrGroupId = groupNameRoleIdMap.get('SuperAdmin');
		grpMem3.GroupId = grp.Id;
		Insert grpMem3; 

		//Create Group And Sub Group Map Data
		Map<String,Id> groupNameRoleAndSubordinatesIdMap = new Map<String,Id>();
		for(Group gp: [SELECT Id, Name FROM Group WHERE Type = 'RoleAndSubordinates']){
			groupNameRoleAndSubordinatesIdMap.put('Admin', gp.Id);
		} 

		//Assign Role To Parent Group
		GroupMember grpMem4 = new GroupMember();
		grpMem4.UserOrGroupId = groupNameRoleAndSubordinatesIdMap.get('Admin');
		grpMem4.GroupId = grp.Id;
		Insert grpMem4;             
		
		//Execute your method here with Group and Group Member Test data
		
		Test.stopTest();
	}
}

Leave a Reply