Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Helper class for determining field change criteria
public with sharing class HelperTriggerUtility {
private SObject newObj;
private SObject oldObj;
public HelperTriggerUtility(SObject oldObj, SObject newObj) {
this.newObj = newObj;
this.oldObj = oldObj;
}
public Boolean hasFieldChanged(String fieldname)
{
if(oldObj.get(fieldname) != newObj.get(fieldname)){
return true;
} else {
return false;
}
}
public Boolean hasAnyFieldChanged(List<String> fieldnames)
{
for(String field : fieldnames){
if(oldObj.get(field) != newObj.get(field)){
return true;
}
}
return false;
}
}
@isTest
private class Test_HelperTriggerUtility {
@isTest static void it_should_return_true_if_specified_field_changed() {
Account oldAct = new Account();
Account newAct = oldAct.clone();
newAct.Name = 'New name';
System.assert(oldAct.Name != newAct.Name);
HelperTriggerUtility helper = new HelperTriggerUtility(oldAct, newAct);
Boolean test = helper.hasFieldChanged('Name');
System.assert(test, 'It should be true');
}
@isTest static void it_should_return_true_if_any_specified_field_is_changed() {
Account oldAct = new Account();
Account newAct = oldAct.clone();
newAct.Name = 'New name';
System.assertNotEquals(oldAct.Name,newAct.Name);
HelperTriggerUtility helper = new HelperTriggerUtility(oldAct, newAct);
List<String> posList = new List<String>{'Name','AnnualRevenue','Industry'};
List<String> negList = new List<String>{'AnnualRevenue','Industry'};
Boolean postive = helper.hasAnyFieldChanged(posList);
Boolean negative = helper.hasAnyFieldChanged(negList);
System.assert(postive, 'It should be true');
System.assert(!negative, 'It should be false');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment