Ninius86
Ninius86

Reputation: 295

How to get assertion result from JsonUnit?

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?

Upvotes: 3

Views: 1327

Answers (1)

Matt
Matt

Reputation: 13923

The method assertThatJson(...) throws an AssertionError if an assertion fails. In this case, the variable jsonAssert does 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 AssertionError and 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).

boolean success;
String message;
try {
    assertThatJson("{\"a\":1, \"b\":2}")
            .when(Option.IGNORING_ARRAY_ORDER)
            .isEqualTo("{b:1, a:1}");
    success = true;
    message = "Assertion successful";
} catch (AssertionError e) {
    success = false;
    message = e.getMessage();
}
System.out.println(success);
System.out.println(message);

Output when successful:

true
Assertion successful

Output when failed:

false
JSON documents are different:
Different value found in node "b", expected: <1> but was: <2>.

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:

public static void main(String[] args) {
    final Result result = getAssertionResult(() -> {
        assertThatJson("{\"a\":1, \"b\":2}")
                .when(Option.IGNORING_ARRAY_ORDER)
                .isEqualTo("{b:2, a:1}");
    });
    System.out.println(result.isSuccess());
    System.out.println(result.getMessage());
}

public static Result getAssertionResult(final Runnable assertion) {
    try {
        assertion.run();
        return new Result(true, "Assertion successful");
    } catch (AssertionError e) {
        return new Result(false, e.getMessage());
    }
}

static class Result {

    private final boolean success;
    private final String message;

    public Result(final boolean success, final String message) {
        this.success = success;
        this.message = message;
    }

    public boolean isSuccess() {
        return success;
    }

    public String getMessage() {
        return message;
    }
}

Upvotes: 2

Related Questions