Bilal
Bilal

Reputation: 588

How to use logger to print messages with assert

I am trying to implement a logger in my repo and I am having some issues with implementing logger with Junit.

Sample assertion:

logger.info("Asserting the response.");
assertThat(response.statusCode())
                    .withFailMessage("The test failed with status code:" + response.statusCode())
                    .isEqualTo(200);

I want to use logger.error() function in place of withFailMessage but I can't seem to find any method.

Upvotes: 1

Views: 1274

Answers (1)

Stefano Cordio
Stefano Cordio

Reputation: 2257

Standard assertions (i.e., assertThat()) are meant to fail immediately with an AssertionError.

If you would like to have custom logic in case of failures, Soft Assertions together with the callback feature might be what you are looking for.

Your example would become something like:

SoftAssertions softly = new SoftAssertions();
softly.setAfterAssertionErrorCollected(error -> logger.error("Assertion failed: {}", error));

softly.assertThat(response.statusCode())
      .isEqualTo(200);

Upvotes: 2

Related Questions