Class Rules
Now there are also class rules in JUnit. A class rule extends the idea of test method-level rules and can be used to add logic, which should be invoked for or after all test methods. A simple use-case could be, when you need a HTTP server in the test, you could have a class rule to start and stop the server. Here a simple code snippet that starts and stops a HTTP server.
Test Sequence
- Start HTTP Server
- Run Test : invokeServletWithRequestOne()
- Run Test : invokeServletWithRequestTwo()
- Stop HTTP Server
Composition of JUnit Rules with RuleChain Feature
In JUnit 4.10 now you can order rules via a rule chain. This is really nice to reuse rules and combine them. Here a simple RuleChain code snippet.
Test Sequence
- Start new Jetty Server (rule = ServerRule)
- Create new Servlet Instance and add it to the Server (rule = ServletRule)
- Run Test : invokeServletWithRequestOne()
- Remove Servlet from Server (rule = ServletRule)
- Stop Jetty Server (rule = ServerRule)
- Start new Jetty Server (rule = ServerRule)
- Create new Servlet Instance and add it to the Server (rule = ServletRule)
- Run Test : invokeServletWithRequestTwo()
- Remove Servlet from Server (rule = ServletRule)
- Stop Jetty Server (rule = ServerRule)
Interface MethodRule is deprecated
The type MethodRule is now deprecated because the name makes no sense anymore because now we have class and method-level rules. A rule now should be of the type TestRule.
Thanks
Thanks at David Saff and Kent Beck for the work on JUnit and the cool rule features we have now in JUnit.
Links
- JUnit GitHub Project - https://github.com/KentBeck/junit
- JUnit Portal - http://www.junit.org/
- Blog Post about JUnit Rule and Logging - http://tux2323.blogspot.com/2011/06/test-logging-via-junit-rule.html