1

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.

Bilal
  • 558
  • 8
  • 18
  • `withFailMessage` only manipulates the error message of the `AssertionError` raised when the assertion fails. I am not sure I understood your target. Would you like to avoid the `AssertionError` and have a logged event instead? – Stefano Cordio Apr 11 '22 at 19:35
  • Yea. Just do the same action but using logger. – Bilal Apr 12 '22 at 23:18

1 Answers1

2

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);
Stefano Cordio
  • 1,687
  • 10
  • 20