Dinky Dinky - 2 months ago 13
JSON Question

Asserting two JSON results that are output in random order

When unit testing, I need to assert two

JSON
results that are output in random order.

Both
JSONs
have the same schema but most contents do vary.

The best idea I have so far is to use a
switch statement
case by case and when a unique value matches the
case label
, do a whole lot of assertions in each case. This seems messy.

Is there a more straight-forward way of handling such situations?

These come from a
Kafka
Stream (
JavaPairDStream
when testing) and are extracted from a
tuple2
then converted from
JSON Strings
to Map using
Jackson ObjectMapper
. I am using
queueStream
but oddly the order is random when testing with
Spark
workflow.

EDIT: I have decided to go with a
List
since a set would change the order... Here is the
Java
code:

//Create a list to store maps
List<Map<String, Object>> list = new ArrayList<>();
list.add(map1);
list.add(map2);

//Traverse each map in list and apply correct assertions
for (Map<String, Object> map : list) {
//if Event is "Event1", assertions for "Event1" Event
if (map.get("Event").toString().equals("Event1")) {
Assert.assertEquals(map.get("Event").toString(), "Event1");
more assertions go here...
} else {
//if Event is not "Event1", assertions for "Event2" Event
Assert.assertEquals(map.get("Event").toString(), "Event2");
more assertions go here...
}
}


Note: This works fine right now since I am only working with two distinct Events. But I would like to learn how to handle this situation with scalability.

Answer

Try the hamcrest matcher containsInAnyOrder. You may have to write a custom matcher to make the code readable.

List<Map<String,Object>> myJsonObjectsInRandomOrder;
...
assertThat(myJsonObjectsInRandomOrder, containsInAnyOrder(new CustomMatcher("Event1", ... ), new CustomMatcher("Event2", ... )));