Skip to content

Add clearer failure messages #52

@M0rfic

Description

@M0rfic

Hi,

Sometimes the failure message message does not express the issue clearly. For example, comparing {"id":"1"} against {"id":"1 "} or {"id": 1} yields

java.lang.AssertionError: id
Expected: 1
 but got: 1

This kept me scratching my head until I realised that there was an extra space or a difference in types. As a quick dirty workaround, I extended the DefaultComparator to also "wrap" the values and print their type:

@Override
    public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException {
        if (expectedValue instanceof Number && actualValue instanceof Number) {
            if (((Number) expectedValue).doubleValue() != ((Number) actualValue).doubleValue()) {
                result.fail(prefix, ((Number) expectedValue).doubleValue(), ((Number) actualValue).doubleValue());
            }
        } else if (expectedValue.getClass().isAssignableFrom(actualValue.getClass())) {
            if (expectedValue instanceof JSONArray) {
                compareJSONArray(prefix, (JSONArray) expectedValue, (JSONArray) actualValue, result);
            } else if (expectedValue instanceof JSONObject) {
                compareJSON(prefix, (JSONObject) expectedValue, (JSONObject) actualValue, result);
            } else if (!expectedValue.equals(actualValue)) {
                result.fail(prefix + "\nExpected: [" + expectedValue + "]\n but got: [" + actualValue + "]");            }
        } else {
            result.fail(prefix + "\nExpected: [" + expectedValue + "] of type [" + expectedValue.getClass() + "]\n but got: [" + actualValue + "] of type [" + actualValue.getClass() + "]");
        }
    }

which now produces:

java.lang.AssertionError: id
Expected: [1]
 but got: [1 ]

and

java.lang.AssertionError: id
Expected: [1] of type [class java.lang.String]
 but got: [1] of type [class java.lang.Integer]

Since I didn't get the chance to familiarize with the code I'm not sure this is the best approach, but I was wondering whether you'd include something similar in a future version, or if this is is acceptable I could provide a push.

Kind regards

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions