I am trying to write assertions to test the iteration of JSON array of objects.
I want to return each key value and use it elsewhere in my application.
For example:
@Before
public void setUp() {
jsonStringSingleObject = "[{\"id\": 1, \"name\": \"A green door\", \"price\": \"12.50\"}]";
jsonStringMultipleObjects = "[{\"id\": 1, \"name\": \"A green door\", \"price\": \"12.50\"}, "
+ "{\"id\": 7, \"name\": \"Tesla\", \"price\": \"94.71\"}]";
}
Which I can then use the following test to check the id key: I am iterating using the good old way as I do not have millions of data to iterate(up 100 max).
@Test
public String idExtractor_checksSingleIDValueWhenPassedAnArrayWithIDKey()
throws JSONException {
JSONArray json = new JSONArray(jsonStringSingle);
for (int i = 0; i < json.length(); i++) {
JSONObject objects = json.getJSONObject(i);
String id = objects.getString("id");
assertTrue(id.equals("1"));
System.out.println(id);
}
}
The test passes with a single object however, when I pass the jsonStringMultipleObject
,
The test fails.
I managed to pass the test using
assertThat(id, anyOf(containsString("1"), containsString("2")));
But this does not resolve the underlying problem. I would like to check the id per object and return it - something like
AssertTrue(id.equals("1")); ///test passes
Then check the second object
AssertTrue(id.equals("2")); ///test passes
TESTS PASSED!
if the first assertion fails, I need the whole test to fail. Would this be possible?