Java Magazine, Nov/Dec 2016
ORACLE COM JAVAMAGAZINE NOVEMBER DECEMBER 2016 27 junit 5 TestExtensionContext context throws Exception This is what the extension looks like public class BenchmarkExtension implements BeforeTestExecutionCallback AfterTestExecutionCallback private long launchTime @ Override public void beforeTestExecution TestExtensionContext context launchTime System currentTimeMillis @ Override public void afterTestExecution TestExtensionContext context long elapsedTime System currentTimeMillis launchTime System out printf Test took d ms n elapsedTime Registering Extensions It is not suficient to implement an extension JUnit also has to know about it An extension can be registered with the @ ExtendWith annotation which can be used on types and methods and takes the extensions class as an argument During test execution JUnit looks for these annotations on test classes and methods and runs all extensions it can find Registering an extension on a single container or method is idempotent meaning registering the same extension multiple times on the same element has no additional effect What about registering the same one on diferent elements Extensions are inherited in the sense that a method inherits all extensions applied to the containing type and a type inherits all the extensions of its supertypes They are applied outside in so for example a before each extension that was registered with a container is executed before extensions to the same point on the executed method The outside in approach as opposed to a top down approach implies that extensions adding after behavior are executed in reverse order That is extensions registered on methods are executed before those registered with the corresponding container Registering different extensions for the same extension point is of course possible as well They are also applied outside in in the order in which they are declared Registering a benchmark extension With that knowledge lets apply a benchmark extension this is the way all methods are benchmarked @ ExtendWith BenchmarkExtension class class BenchmarkedTest @ Test void benchmarked throws InterruptedException Thread sleep 100 Stores are hierarchical because a store is created for each extension context which means there is one store per node in the test tree
You must have JavaScript enabled to view digital editions.