I have two instances of one custom object and want to compare all of their fields to make sure they are exactly the same. I have the code below:

CustomObject__c validCustomObject = new CustomObject__c(...);
CustomObject__c queriedCustomObject = [SELECT ... FROM CustomObject__c WHERE Name validCustomObject.Name];
System.assertEquals(validCustomObject, queriedCustomObject);

But the assertion fails. I have confirmed that the two variables have exactly the same fields and ids and want to find a way to compare them. I can build an equals() method but is there such a method for sObjects so I don't need to implement it myself?

| improve this question | | | | |
  • 2
    A difference in a single field - an Id in one instance and no Id in the other instance or a single field queried in one instance but not set in the other - makes the objects not equal. I've tried to rely on the built in equals logic, but have always ended up writing my own method so I can restrict the logic to the fields that matter for the business logic – Keith C Feb 27 '18 at 21:58

Equals does work (e.g. validCustomObject == queriedCustomObject), but remember that queries include hidden fields, so you'd have to also include those fields in those constructed objects. It's usually easier to just construct a record from the query, then use equals() or == on the constructed object:

CustomObject__c queriedObject = [...];
CustomObject__c compareObject = new CustomObject__c(Field1=queriedObject.Field1...);
System.assertEquals(validCustomObject, compareObject);

This is marginally faster than writing your own equals method.

| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.