The document discusses JUnit 5, the next generation of the JUnit testing framework for Java. Key aspects include a new programming model using extensions, support for Java 8 features, and ways to migrate from earlier JUnit versions. The new framework consists of the JUnit Platform launcher, the JUnit Jupiter API for writing tests, and the JUnit Vintage engine for running JUnit 3 and 4 tests.
24. @TestInstance
Controls lifecycle of test instances
Per method is the default;
creates new instance for every test
Per class re-uses the same
instance for every test
26. @TestInstance
In general, stick with the default
PER_METHOD lifecycle…
…and become aware of
differences (pitfalls?) in behavior
when using PER_CLASS
33. Dependency Injection
Constructors & methods can have parameters!
DIY using ParameterResolver API
Several built-in resolvers
(TestInfo, RepetitionInfo, and TestReporterParameterResolver)
36. A word on Assertions
Jupiter provides the basics…
…and several more useful ones
But consider using 3rd party
assertion frameworks like AssertJ,
Hamcrest, or Google’s Truth
(asssertAll, assertTimeout, assertThrows, etc.)
48. @Slf4j
public class SoftAssertionsExtension
extends SoftAssertions implements AfterEachCallback {
public SoftAssertionsExtension() {
LOG.trace("Constructed new instance");
}
public void afterEach(ExtensionContext context) {
LOG.trace("Asserting all soft assertions”);
assertAll();
}
}
SoftAssertions is an AssertJ class
49. More extension features
Automatic registration via ServiceLoader
Keeping state via ExtensionContext.Store
ParameterResolver for resolving parameters
Test instance post-processing
Conditional test execution
(disabled by default)
51. No @Rules
Without any rules, it’s pretty easy!
…mostly changing imports
…and some annotations, e.g.
@Before to @BeforeEach
52. With @Rules
With existing rules, it depends…
Converting most rules is fairly easy
Many frameworks already have
JUnit 5 extensions
(e.g. Dropwizard, Spring, Mockito, …)
53. Migration Support
Must use @EnableRuleMigrationSupport
Includes support for:
ExternalResource
ExpectedException
Verifier (including ErrorCollector)
(*)
(*) this probably covers a lot of existing rules
54. APIs
Support API evolution over time
Mark public interface with @API status
Uses @APIGuardian for status, e.g.
STABLE, INTERNAL, EXPERIMENTAL
55. Wrap up
New programming & extension model
Allows migration over time and
keeping JUnit 4 & 5 in same project
Separates platform from test engines
Recommend use 3rd-party assertion library
57. References
JUnit 5 on GitHub
https://github.com/junit-team/junit5
@API Guardian
https://github.com/apiguardian-team/apiguardian
JUnit 5 web site
https://junit.org/junit5/
JUnit 5 User Guide
https://junit.org/junit5/docs/current/user-guide/