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
Ellsa JamesEllsa James 

I need some help writing a test class to get coverage

I have written the below trigger and helper class that adds a partner user to a specific public group when a checkbox is ticked on the contact record.

Trigger
trigger Addtogroup4 on Contact (after insert, after update) {
      
      List<GroupMember> GMlist = new List<GroupMember>();
       Set<String> contactEmails = new Set<String>();
       for(Contact con : Trigger.New) {
          //create a set with the contact email addresses
          contactEmails.add(con.email);
       }
    
       //query for the related users and put them in a map,
       //where the key is the email and the value is the user
       Map<String, User> emailUserMap = new Map<String, User> ();
       for(User aUser : [select id, email from User where email in : contactEmails]){
          emailUserMap.put(aUser.email, aUser);
       }
           system.debug(emailUserMap);
           List<Id> userIdList = new List<Id>();
      for(Contact con : Trigger.New) {
        if(con.Public_Group_Technology_Partner_Content__c == TRUE) {    
              
             userIdList.add(emailUserMap.get(con.email).id);
    
          }
      }  
   
      //dymanically get the get group id.
      Group theGroup = [select id from Group where Name = 'Technology Partner Content'];
      if(null != theGroup){
          //call the contact trigger helper if the group exists. 
          //This method adds the user to the group
          ContactTriggerHelper.addUsersToGroup(theGroup.id,userIdList );
      }
  }

Helper Class
public class ContactTriggerHelper{
       
      //future call to do the group adding.  the future call will spawn a new thread.
      @future
      public static void addUsersToGroup(String groupId, List<Id> userIds){
          List<GroupMember> GMlist = new List<GroupMember>();
          for(ID userId: userIds){
              GroupMember gm = new GroupMember();
              gm.GroupId = groupId;
              gm.UserOrGroupId = userId;
              gmList.add(GM);
          }
      
       
          if(gmList.size() > 0){
              insert gmList;
          }
      }
    
  }

The trigger and class are working fine in sandbox. The problem is I am a newbie to apex and have no Idea how to write the test class for this. I pieced the trigger and clas together with assistance on this forum. Do I need a test class for the class and the trigger? Can anyone advise what it would look like?

Thank you
Best Answer chosen by Ellsa James
Arunkumar RArunkumar R
Hi Ellasa,

In your trigger Line no 27 i.e Group theGroup = [select id from Group where Name = 'Technology Partner Content'];

Add the Limit in your query , Group theGroup = [select id from Group where Name = 'Technology Partner Content' Limit 1];


Then copy paste the below test class it will give 100% coverage.

@isTest
private class AddtoGroupTest
{
    static testMethod void createGroup()
    {
 User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
      System.runAs (thisUser) 
      {        // Insert user
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
        User u = new User(Alias = 'standt', Email='test@test.com', 
        EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
        LocaleSidKey='en_US', ProfileId = p.Id, 
        TimeZoneSidKey='America/Los_Angeles', UserName='sdss123@test.com');
        insert u;
        
        // Insert group
        Group grp = new Group();
        grp.Name = 'Technology Partner Content';
        insert grp;
 
        
        // Insert contact with your required field.
        Contact cnt = new Contact();
        cnt.LastName = 'Test contact';
        cnt.Email = 'test@test.com';
        cnt.Public_Group_Technology_Partner_Content__c = true;
        insert cnt;
        }

    }
    

}

Please mark it as Best solutions if it's works for you...!

Thanks

All Answers

Fabien TaillonFabien Taillon
You need only one test class.
The idea is to :
  • Create the data needed
  • Use Test.startTest()/Test/stopTest()
  • Insert/Update your test contacts so that they match your triggers criteria
  • Assert that the result is the one you expected
If you're new to test classes, you should definitely read this :
https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods

Also, if you want to find the Users linked to Contacts, you should use the ContactId field on User object instead of the email.
Arunkumar RArunkumar R
Hi Ellsa,

Here is your test class, It will helpful to you...

@isTest
private class AddtoGroupTest
{
	static void createGroup(Boolean isGroup)
	{

		// Insert contact with your required field.
		Contact cnt = new Contact();
		cnt.LastName = 'Test contact';
		cnt.Email = 'test@test.com';
		cnt.Public_Group_Technology_Partner_Content__c  = true;
		insert cnt;


		// Insert user

		Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
		User u = new User(Alias = 'standt', Email='test@test.com', 
		EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
		LocaleSidKey='en_US', ProfileId = p.Id, 
		TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');
		insert u;

		// Insert Group
		if(isGroup == true)
		{
			Group grp = new Group();
			grp.Name = 'Technology Partner Content';
			grp.DeveloperName = 'Technology Partner Content';
			insert grp;
		}
	}
	

	static testMethod void insertWithGroup()
	{
		createGroup(true);
	}

	static testMethod void insertWithoutGroup()
	{
		createGroup(false);
	}
}


Ellsa JamesEllsa James
Thanks Arukumar,

I have tried the test class but am getting the below error when running tests

""System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Addtogroup4: execution of AfterInsert

caused by: System.NullPointerException: Attempt to de-reference a null object

Trigger.Addtogroup4: line 21, column 1: []""

Any idea?
Harish GSHarish GS

Hi , Ellsa James
"System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Addtogroup4: execution of AfterInsert

This is the Exception ,you have to handle the Exception , so use Try and catch block while doing dml operation... ex:try
{
insert grp;
}catch( execption e){ System.debug(e)};

Check ,i Think it May Work


 

 

Ellsa JamesEllsa James
Where in the code should I add this?
Arunkumar RArunkumar R
Hi Ellasa,

In your trigger Line no 27 i.e Group theGroup = [select id from Group where Name = 'Technology Partner Content'];

Add the Limit in your query , Group theGroup = [select id from Group where Name = 'Technology Partner Content' Limit 1];


Then copy paste the below test class it will give 100% coverage.

@isTest
private class AddtoGroupTest
{
    static testMethod void createGroup()
    {
 User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
      System.runAs (thisUser) 
      {        // Insert user
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
        User u = new User(Alias = 'standt', Email='test@test.com', 
        EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
        LocaleSidKey='en_US', ProfileId = p.Id, 
        TimeZoneSidKey='America/Los_Angeles', UserName='sdss123@test.com');
        insert u;
        
        // Insert group
        Group grp = new Group();
        grp.Name = 'Technology Partner Content';
        insert grp;
 
        
        // Insert contact with your required field.
        Contact cnt = new Contact();
        cnt.LastName = 'Test contact';
        cnt.Email = 'test@test.com';
        cnt.Public_Group_Technology_Partner_Content__c = true;
        insert cnt;
        }

    }
    

}

Please mark it as Best solutions if it's works for you...!

Thanks
This was selected as the best answer
Harish GSHarish GS
Hi , Ellsa James

In Your
public class ContactTriggerHelper{       

      //future call to do the group adding.  the future call will spawn a new thread.
      @future
      public static void addUsersToGroup(String groupId, List<Id> userIds){
          List<GroupMember> GMlist = new List<GroupMember>();
          for(ID userId: userIds){
              GroupMember gm = new GroupMember();
              gm.GroupId = groupId;
              gm.UserOrGroupId = userId;
              gmList.add(GM);
          } 
              if(gmList.size() > 0)
             {
                try {
                      insert gmList;
                     }catch(DmlException e)
                       {
                          System.debug('The following exception has occurred: ' + e.getMessage());
                        }
              }
      }
   

  }
Please check it may work.. after writeing test class..... if its working let me know


Thankyou.....