/** * Asserts that the JSONObject provided matches the expected JSONObject. If it isn't it throws an * {@link AssertionError}. * * @param message Error message to be displayed in case of assertion failure * @param expected Expected JSONObject * @param actual JSONObject to compare * @param compareMode Specifies which comparison mode to use * @throws JSONException JSON parsing error */ public static void assertEquals(String message, JSONObject expected, JSONObject actual, JSONCompareMode compareMode) throws JSONException { JSONCompareResult result = JSONCompare.compareJSON(expected, actual, compareMode); if (result.failed()) { throw new AssertionError(getCombinedMessage(message, result.getMessage())); } }
/** * Asserts that the json string provided does not match the expected string. If it is it throws an * {@link AssertionError}. * * @param message Error message to be displayed in case of assertion failure * @param expectedStr Expected JSON string * @param actualStr String to compare * @param comparator Comparator * @throws JSONException JSON parsing error */ public static void assertNotEquals(String message, String expectedStr, String actualStr, JSONComparator comparator) throws JSONException { JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, comparator); if (result.passed()) { throw new AssertionError(getCombinedMessage(message, result.getMessage())); } }
if (compareJSON((JSONObject) expectedElement, (JSONObject) actualElement).passed()) { matched.add(j); matchFound = true; if (compareJSON((JSONArray) expectedElement, (JSONArray) actualElement).passed()) { matched.add(j); matchFound = true; result.fail(key + "[" + i + "] Could not find match for element " + expectedElement); return;
/** * Identify the missing field * @param field missing field * @param expected expected result * @return result of comparison */ public JSONCompareResult missing(String field, Object expected) { _fieldMissing.add(new FieldComparisonFailure(field, expected, null)); fail(formatMissing(field, expected)); return this; }
/** * Identify unexpected field * @param field unexpected field * @param actual actual result * @return result of comparison */ public JSONCompareResult unexpected(String field, Object actual) { _fieldUnexpected.add(new FieldComparisonFailure(field, null, actual)); fail(formatUnexpected(field, actual)); return this; }
/** * Identify that the comparison failed * @param field Which field failed * @param expected Expected result * @param actual Actual result * @return result of comparision */ public JSONCompareResult fail(String field, Object expected, Object actual) { _fieldFailures.add(new FieldComparisonFailure(field, expected, actual)); this._field = field; this._expected = expected; this._actual = actual; fail(formatFailureMessage(field, expected, actual)); return this; }
static JSONComparisonResult resultOf(JSONCompareResult result) { if (result.failed()) { return diagnose(result); } else { return comparisonPassed(); } }
@Override public boolean matches(Object item) { if (!(item instanceof String)) { ObjectMapper om = new ObjectMapper(); try { item = om.writeValueAsString(item); } catch (JsonProcessingException e) { failureMessage = e.getMessage(); return false; } } JSONCompareResult result; try { result = JSONCompare.compareJSON(expectedJson, item.toString(), JSONCompareMode.LENIENT); } catch (JSONException jex) { failureMessage = jex.getMessage(); return false; } if (result != null && result.failed()) { failureMessage = result.getMessage(); } return result != null && result.passed(); }
result.fail(String.format("%s[]\nArrays length differs. Expected length=%d but actual length=%d\n", prefix, expected.length(), actual.length())); return; JSONCompareResult tmpResult = new JSONCompareResult(); compareValues(prefix + "[" + i + "]", expectedValue, actualValue, tmpResult); if (tmpResult.passed()) { isEquals = true; actValueMostlySimilarIndex = j; break; if (tmpResult.getFieldFailures().size() < minErrorsCount) { minErrorsCount = tmpResult.getFieldFailures().size(); actValueMostlySimilar = actualValue; actValueMostlySimilarIndex = j; JSONCompareResult tmpResult = new JSONCompareResult(); super.compareJSON(prefix + "[" + i + "]", expectedValue, actValueMostlySimilar, tmpResult); result.fail(tmpResult.getMessage());
@Override public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException { if (areNumbers(expectedValue, actualValue)) { if (areNotSameDoubles(expectedValue, actualValue)) { result.fail(prefix, expectedValue, actualValue); } } 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, expectedValue, actualValue); } } else { result.fail(prefix, expectedValue, actualValue); } }
/** * Compares {@link JSONString} provided to the expected {@code JSONString}, checking that the * {@link org.json.JSONString#toJSONString()} are equal. * * @param expected Expected {@code JSONstring} * @param actual {@code JSONstring} to compare * @return result of the comparison */ public static JSONCompareResult compareJson(final JSONString expected, final JSONString actual) { final JSONCompareResult result = new JSONCompareResult(); final String expectedJson = expected.toJSONString(); final String actualJson = actual.toJSONString(); if (!expectedJson.equals(actualJson)) { result.fail(""); } return result; }
protected void compareJSONArrayOfSimpleValues(String key, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException { Map<Object, Integer> expectedCount = JSONCompareUtil.getCardinalityMap(jsonArrayToList(expected)); Map<Object, Integer> actualCount = JSONCompareUtil.getCardinalityMap(jsonArrayToList(actual)); for (Object o : expectedCount.keySet()) { if (!actualCount.containsKey(o)) { result.missing(key + "[]", o); } else if (!actualCount.get(o).equals(expectedCount.get(o))) { result.fail(key + "[]: Expected " + expectedCount.get(o) + " occurrence(s) of " + o + " but got " + actualCount.get(o) + " occurrence(s)"); } } for (Object o : actualCount.keySet()) { if (!expectedCount.containsKey(o)) { result.unexpected(key + "[]", o); } } }
@Override public void describeTo(Description description) { boolean first = true; for (FieldComparisonFailure failure : result.getFieldFailures()) { if (!first) description.appendText(" and "); description .appendText("field ").appendText(failure.getField()) .appendText(" was ").appendValue(failure.getActual()) .appendText(" instead of ").appendValue(failure.getExpected()); first = false; } if (result.getFieldFailures().isEmpty()) { description.appendText(result.getMessage()); } } });
private JSONCompareResult compareForNull(CharSequence expectedJson) { JSONCompareResult result = new JSONCompareResult(); result.passed(); if (expectedJson != null) { result.fail("Expected null JSON"); } return result; }
@Test public void structMissingItemsInArray() throws JSONException { final JSONObject object1 = (JSONObject) JSONParser.parseJSON("{ \"a\": [ 1, 2 ] }"); final JSONObject object2 = (JSONObject) JSONParser.parseJSON("{ \"a\": [ 1 ] }"); final JSONCompareResult results = JSONCompare.compareJSON(object1, object2, new RegularExpressionJSONComparator(JSONCompareMode.STRICT)); Assert.assertTrue(results.failed()); Assert.assertEquals(1, results.getFieldMissing().size()); Assert.assertEquals(0, results.getFieldUnexpected().size()); }
/** * Compares the item (which represents the actual result) against the expected value to see if they are the same JSON. These two * values * may not be equal as Strings, but the JSON comparison should ignore unnecessary whitespace and the differences between " and '. * * @param item a String containing valid JSON to compare against the expected value * @return true if the expected and actual values are equivalent JSON values */ @Override public boolean matchesSafely(final String item) { try { return JSONCompare.compareJSON(expectedJson, item, JSONCompareMode.STRICT).passed(); } catch (final JSONException e) { Assert.fail(String.format("JSON compare threw exception when trying to compare %n %s %n with %n %s%n Exception was: %n%s ", expectedJson, item, e)); return false; } }
protected void compareJSONArrayOfJsonObjects(String key, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException { String uniqueKey = findUniqueKey(expected); if (uniqueKey == null || !isUsableAsUniqueKey(uniqueKey, actual)) { // An expensive last resort recursivelyCompareJSONArray(key, expected, actual, result); return; } Map<Object, JSONObject> expectedValueMap = arrayOfJsonObjectToMap(expected, uniqueKey); Map<Object, JSONObject> actualValueMap = arrayOfJsonObjectToMap(actual, uniqueKey); for (Object id : expectedValueMap.keySet()) { if (!actualValueMap.containsKey(id)) { result.missing(formatUniqueKey(key, uniqueKey, id), expectedValueMap.get(id)); continue; } JSONObject expectedValue = expectedValueMap.get(id); JSONObject actualValue = actualValueMap.get(id); compareValues(formatUniqueKey(key, uniqueKey, id), expectedValue, actualValue, result); } for (Object id : actualValueMap.keySet()) { if (!expectedValueMap.containsKey(id)) { result.unexpected(formatUniqueKey(key, uniqueKey, id), actualValueMap.get(id)); } } }
/** * Compares JSONObject provided to the expected JSONObject, and returns the results of the comparison. * * @param expected Expected JSONObject * @param actual JSONObject to compare * @throws JSONException JSON parsing error */ @Override public final JSONCompareResult compareJSON(JSONObject expected, JSONObject actual) throws JSONException { JSONCompareResult result = new JSONCompareResult(); compareJSON("", expected, actual, result); return result; }
protected void checkJsonObjectKeysExpectedInActual(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) throws JSONException { Set<String> expectedKeys = getKeys(expected); for (String key : expectedKeys) { Object expectedValue = expected.get(key); if (actual.has(key)) { Object actualValue = actual.get(key); compareValues(qualify(prefix, key), expectedValue, actualValue, result); } else { result.missing(prefix, key); } } }
static JSONComparisonResult resultOf(JSONCompareResult result) { if (result.failed()) { return diagnose(result); } else { return comparisonPassed(); } }