Skip to content

Commit 9771c19

Browse files
committed
Merge pull request skyscreamer#6 from twr/master
Handling cases where when of the values is null or values have different types
2 parents 3d25774 + 7109e89 commit 9771c19

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/main/java/org/skyscreamer/jsonassert/JSONCompare.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,31 @@ else if (expectedValue instanceof JSONObject) {
112112
else if (!expectedValue.equals(actualValue)) {
113113
result.fail(fullKey, expectedValue, actualValue);
114114
}
115+
} else {
116+
if (isNull(expectedValue)) {
117+
result.fail(fullKey + ": expected null, but got " + classToType(actualValue));
118+
} else if (isNull(actualValue)) {
119+
result.fail(fullKey + ": expected " + classToType(expectedValue) + ", but got null");
120+
} else {
121+
result.fail("Values of " + fullKey + " have different types: expected " + classToType(expectedValue)
122+
+ ", but got " + classToType(actualValue));
123+
}
124+
}
125+
}
126+
127+
private static boolean isNull(Object value) {
128+
return value.getClass().getSimpleName().equals("Null");
129+
}
130+
131+
private static String classToType(Object value) {
132+
if (value instanceof JSONArray) {
133+
return "an array";
134+
} else if (value instanceof JSONObject) {
135+
return "an object";
136+
} else if (value instanceof String) {
137+
return "a string";
138+
} else {
139+
return value.getClass().getName();
115140
}
116141
}
117142

src/test/java/org/skyscreamer/jsonassert/JSONAssertTest.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,23 @@ public void testArrayOfArrays() throws JSONException {
136136
testPass("{id:1,stuff:[[4,3],[3,2],[],[1,2]]}", "{id:1,stuff:[[1,2],[2,3],[],[3,4]]}", false);
137137
}
138138

139+
@Test
140+
public void testNullProperty() throws JSONException {
141+
testFail("{id:1,name:\"Joe\"}", "{id:1,name:null}", true);
142+
testFail("{id:1,name:null}", "{id:1,name:\"Joe\"}", true);
143+
}
144+
145+
@Test
146+
public void testIncorrectTypes() throws JSONException {
147+
testFail("{id:1,name:\"Joe\"}", "{id:1,name:[]}", true);
148+
testFail("{id:1,name:[]}", "{id:1,name:\"Joe\"}", true);
149+
}
150+
151+
@Test
152+
public void testNullEquality() throws JSONException {
153+
testPass("{id:1,name:null}", "{id:1,name:null}", true);
154+
}
155+
139156
private void testPass(String expected, String actual, boolean strict)
140157
throws JSONException
141158
{

0 commit comments

Comments
 (0)