You need to sign in to do that
Don't have an account?
Lakshmi S
How to write test class for this Trigger?
HI Team,
Need test class for below trigger.
Thaks
Lakshmi.
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.
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.
Let us know if this will help you