Search code examples
javajsonunit-testingswitch-statementassert

Asserting two JSON results that are output in random order


When unit testing, I need to assert two JSON results that populate a map in random order.

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

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 use a List since a set might 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.


Solution

  • 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", ... )));