I'm working on a test-framework where I'd like to use JsonUnit for comparing two JSONs. My assertion looks like this:
JsonAssert jsonAssert = assertThatJson("{\"a\":1, \"b\":2}")
.when(Option.IGNORING_ARRAY_ORDER)
.isEqualTo("{b:2, a:1}");
Is there a way to extract a boolean value and comparison message from JsonAssert object?
The method
assertThatJson(...)throws anAssertionErrorif an assertion fails. In this case, the variablejsonAssertdoes not have a value assigned and you cannot extract something.However, you can wrap your assertion in a try-catch block and build the logic you want around it. Therefore, catch the
AssertionErrorand then extract the message. You can set a boolean to true inside the try-block (in case of success) or to false inside the catch-block (in case of failure).Output when successful:
Output when failed:
If you want to make this reusable, one option is to create a helper method (
getAssertionResult) that returns the result as a custom object (Result) and takes a lambda to evaluate a given assertion inside a try-catch-block. Here is an example which returns the same output as shown above: