I have created an Apex Class to compare the current and prior values of SObjects. If differences are found the field labels are outputted to a ; separated string which I am using to populate a Multi-select Picklist.
This is working fine when run against real data however is failing in Test with the error "SObject row was retrieved via SOQL without querying the requested field" This is because the test SObjects I am inserting for newObject & priorObject contain the bare minimum of fields and there are a lot if fields on this Object.
Is there a way I can adjust the Class so it elegantly skips the missing fields? Could I base the fieldMap on the fields in the newObject or priorObject rather than the Object definition?
public with sharing class CompareRecords {
public static String CompareRecords(String objectName, SObject newObject, SObject priorObject) {
SObjectType objToken = Schema.getGlobalDescribe().get(objectName);
DescribeSObjectResult objDef = objToken.getDescribe();
Map<String, SObjectField> fieldMap = objDef.fields.getMap();
System.Debug('fieldMap = '+ fieldMap);
List<String> fieldsList = new List<String>();
for (String field : fieldMap.keySet()){
if(
(fieldMap.get(field).getDescribe().isUpdateable()
|| fieldMap.get(field).getDescribe().isCreateable()
)
){
if(
newObject.get(field) != (priorObject.get(field))
){
fieldsList.add(
fieldMap.get(field).getDescribe().getLabel()
);
}
}
}
String fieldsUpdated = string.join(fieldsList,';');
return fieldsUpdated;
}
}