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
Lakshmi SLakshmi S 

How to write test class for this Trigger?

HI Team,
Need test class for below trigger.
trigger HRSFHistoryTracker on High_Risk_Success_Factors__c (after update) {
    
    if(checkRecursive.runOnce()){
        
        try{
            
            Set<Id> userIds = new Set<Id>();
            for(High_Risk_Success_Factors__c hrsf : trigger.new){
                userIds.add(hrsf.CreatedById);
            }
            Map<Id,User> userMap = new Map<Id,User>([Select id,name,userrole.name from User where id in :userIds]);
            
            final List<Schema.FieldSetMember> trackedFields = SObjectType.High_Risk_Success_Factors__c.FieldSets.HRSF_History_Tracking.getFields();
            if(trackedFields.isEmpty())
                return;
            
            final List<HRSF_History_Tracking__c> fieldChanges = new List<HRSF_History_Tracking__c>();
            if(!trigger.isUpdate)
                return;
            
            for(High_Risk_Success_Factors__c newHRSF : trigger.new){
                
                final High_Risk_Success_Factors__c oldHRSF = trigger.oldmap.get(newHRSF.Id);
                
                for(Schema.FieldSetMember fsm : trackedFields){
                    
                    String fieldName = fsm.getFieldPath();
                    String fieldLabel = fsm.getLabel();
                    
                    if(newHRSF.get(fieldName) == oldHRSF.get(fieldName))
                        continue;
                    String oldValue = String.valueOf(oldHRSF.get(fieldName));
                    String newValue = String.valueOf(newHRSF.get(fieldName));
                    
                    if(oldValue != null && oldValue.length()>255)
                        oldValue = oldValue.substring(0, 255);
                    
                    if(newValue != null && newValue.length()>255)
                        newValue = newValue.substring(0,255);
                    
                    final HRSF_History_Tracking__c hrsfHistory = new HRSF_History_Tracking__c();
                    
                    hrsfHistory.Name = fieldLabel;
                    hrsfHistory.APIName__c = fieldName;
                    hrsfHistory.RecordId__c = newHRSF.Id;
                    hrsfHistory.High_Risk_Success_Factor_Name__c = newHRSF.Name;
                    hrsfHistory.ChangedBy__c = userMap.get(newHRSF.CreatedById).userrole.name;
                    hrsfHistory.OldValue__c = oldValue;
                    hrsfHistory.NewValue__c = newValue;
                    hrsfHistory.HRSF_Owner_Name__c= userMap.get(newHRSF.CreatedById).Name;
                    
                    fieldChanges.add(hrsfHistory);
                }
            }
            if(!fieldChanges.isEmpty()){
                insert fieldChanges;
            }
            
        }
        Catch(Exception ex){
            ApexPages.addMessages(ex);
        }

    }
}
Can anyone please let me know how to write the Test Class.

Thaks
Lakshmi.
 
 
Amit Chaudhary 8Amit Chaudhary 8
I will recommend you to start using trailhead to learn about test classes
1) https://trailhead.salesforce.com/modules/apex_testing

Pleasse check below post sample test class
1) http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html

Also please check below post
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm
2) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_example.htm


You write a test class for this the same way that you would any other:
- Set up some data for the Trigger to access
- Verify the behaviour with asserts.

Try below sample test class.
 
@isTest 
public class HRSFHistoryTrackerTest 
{
    static testMethod void testMethod1() 
	{
			High_Risk_Success_Factors__c obj = new High_Risk_Success_Factors__c();
			obj.Name ='Test';
			// add all required field
			insert obj;
			
			Test.StartTest();
			
				update obj;
			
			Test.StopTest();
			
		
    }
}

Let us know if this will help you

 
Raj VakatiRaj Vakati
Use below code
 
@isTest 
public class HRSFHistoryTrackerTest 
{
    static testMethod void testMethod1() 
	{
			
	  Profile ps = [select id, name from Profile where name = 'System Administrator'];

      User standard = new User(alias = 'standt', 
      email='standarduser@testorg.com', 
      emailencodingkey='UTF-8', 
      lastname='Testing', languagelocalekey='en_US', 
      localesidkey='en_US', 
      profileid = ps.Id, 
      timezonesidkey='America/Los_Angeles', 
      username='standarduser@testorg.com');

      insert standard;

    

      system.runas(standard){
       High_Risk_Success_Factors__c obj = new High_Risk_Success_Factors__c();
			obj.Name ='Test';
obj.APIName__c='';
obj.High_Risk_Success_Factor_Name__c =''
obj.HRSF_Owner_Name__c=''; 
			insert obj;
			
			Test.StartTest();
			
			obj.APIName__c='YOUR API NAME_UPDATE';
obj.High_Risk_Success_Factor_Name__c ='UPDATE VALUE'
obj.HRSF_Owner_Name__c='TEST USER'; 
			
			update obj;
			Test.StopTest();
			

      }
			
		
    }
}