JUnit 4 and 5
Junit 4 has been released in 2006 and Junit 5 in 2017. Despite that, Junit 4 usually remains the default today. Here is a short and intuitive summary of the major reasons to migrate to Junit 5.
1. Lambdas
Lambdas allow you to write more intuitive assertions and assumptions (although old-style syntax is fully supported). You can also group assertions. This:
1 | Assume.assumeTrue(testMessage.getProtocol().equals("HTTP")); |
may become:
1 | Assumptions.assumingThat(testMessage.getProtocol().equals(("HTTP"), |
2. @Tag
@Tag replaces @Category, saving the need to define interfaces:
1 | public interface OnlyRunWithIntegrationTests { |
becomes
1 | public class TestsJunit5 { |
Both can for example be used through command line parameters or IDE integration. This allows granular control in defining test groups, which can be useful in particular in integration test suites.
3. @Nested:
This annotation allows you to write logically grouped tests and define shared logic or attributes for these groups. For example:
1 | public class DBTests { |
Conclusion
There are other future-proofing reasons to use Junit 5 over 4, and projects can mix between them so it’s better to get used to the future testing platform.
With that said, the advantages of Junit 5 are minor unless you need them, which justifies its relatively slow adoption. But thanks to the retro-compatibility of Junit 5, a migration is not necessary or it can be done progressively and painlessly while bringing immediate benefits.