Is it possible to somehow intercept the logging (SLF4J + logback) and get an InputStream
(or something else that is readable) via a JUnit test case...?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
The Slf4j API doesn't provide such a way but Logback provides a simple solution.
You can use
ListAppender
: a whitebox logback appender where log entries are added in apublic List
field that we could use to make our assertions.Here is a simple example.
Foo class :
FooTest class :
You can also use Matcher/assertion libraries as AssertJ or Hamcrest.
With AssertJ it would be :
You can create a custom appender
and configure logback-test.xml to use it. Now we can check logging events from our test:
I had problems when testing logs line like: LOGGER.error(message, exception).
The solution described in http://projects.lidalia.org.uk/slf4j-test/ tries to assert as well on the exception and it is not easy (and in my opinion worthless) to recreate the stacktrace.
I resolved in this way:
This has as well the advantage to not having depend on Hamcrest matchers library.
You can use slf4j-test from http://projects.lidalia.org.uk/slf4j-test/. It replaces the entire logback slf4j implementation by it's own slf4j api implementation for tests and provides an api to assert against logging events.
example:
Although creating a custom logback appender is a good solution, it is only the first step, you will eventually end up developing/reinventing slf4j-test, and if you go a bit further: spf4j-slf4j-test or other frameworks that I don't know of yet.
You will eventually need to worry about how many events you keep in memory, fail unit tests when a error is logged (and not asserted), make debug logs available on test failure, etc...
Disclaimer: I am the author of spf4j-slf4j-test, I wrote this backend to be able to better test spf4j, which is a good place to look at for examples on how to use spf4j-slf4j-test. One of the main advantages I achieved was reducing my build output (which is limited with Travis), while still having all the detail I need when failure happens.