Freitag, 3. Juni 2011

Test Logging via JUnit Rule

In most cases it is not necessary to test logging, but in some situations you wont to check in a JUnit test that a log statement will be written, e.g in special error cases. When you use logback as logging framework the test can setup a ListAppender for a Logger and can implement a assert method which checks that the expected log statement is in the ListAppender list. But then the test is logback specific and has dependency on logback! When you use this approache in many JUnit test classes the test source has a hard dependency on logback and when you wont to change the logging framework all tests must also be changed. To remove this hard dependency you can use a JUnit rule, which capsulate the logback framework from the test source. The example here shows how a test and such a JUnit rule can look like.

Here the sample test for verify logging:

And here the logback specific rule:


  1. I am new to @Rule annotation which seems to be introduced in JUnit 4.7. But when researching on the topic of testing exceptions, I also came across this guy who is saying that his magic test library can allow for testing exceptions in pre 4.7 versions too. See the blog post: magic test, specially the table shown by him on that page. Would like to know your comments on the same. Also since I am beginner on JUnit, I also see that @Rule annotation can be applied for timeout of unit tests. So it means that @Rule is a generic annotation and we can use it for multiple purposes. right!

    1. Rules are a way to reuse testing logic by composite instead of inheritance. Rules can be used to reuse e.g. setup or teardown logic in tests. Rules are great to check exceptions for that use the JUnit Rule ExpectedException (see