[SalesForce] assertEquals | All Object Properties Are the Same but the Assertion Fails

In my tests I create an object and compare it to the one returned in the function using System.assertEquals. Despite all the properties being exactly the same I still get the "Assertion Failed" message when comparing objects.

Message:

System.AssertException: Assertion Failed: Expected:
Attribute:[name=Name, options=null, required=false, showInUI=true,
type=String, value=], Actual: Attribute:[name=Name, options=null,
required=false, showInUI=true, type=String, value=]

Notice that Expected and Actual are exactly the same.

Note: all properties are primitive types except options which is a list of Strings.

Best Answer

I resolved this by overriding the equals method for my class as described in the documentation: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections_maps_keys_userdefined.htm

This is what it looks like:

public Boolean equals(Object obj){
    if (obj instanceof SchemaAttribute) {
        SchemaAttribute schemaAttrObj = (SchemaAttribute) obj;
        return required == schemaAttrObj.required && 
        showInUI == schemaAttrObj.showInUI && 
        name == schemaAttrObj.name && 
        value == schemaAttrObj.value && 
        options == schemaAttrObj.options && 
        type == schemaAttrObj.type;
    }
    return false;
}
Related Topic