Java Magazine, Nov/Dec 2016
ORACLE COM JAVAMAGAZINE NOVEMBER DECEMBER 2016 26 junit 5 However from a coding point of view this is generally specified in the location marked in the preceding code 4 The @ BeforeAll formerly @ BeforeClass methods are called if this is the first test from the container 5 The @ BeforeEach formerly @ Before methods are called 6 Test method parameters are resolved Note that test methods can now have parameters 7 The test is executed 8 Possible exceptions are handled 9 The @ AfterEach formerly @ After methods are called 10 The @ AfterAll formerly @ AfterClass methods are called if this is the last test from the container Now lets see how to interact with that lifecycle Extension Points When the JUnit 5 project came together in 2015 the main designers decided on a couple of core principles one of which was this prefer extension points over features And quite literally JUnit 5 has extension points So when a test steps through the lifecycle described above JUnit pauses at defined points and checks which extensions want to interact with the running test at that particular step Heres a list of the extension points ContainerExecutionCondition TestInstancePostProcessor TextExecutionCondition BeforeAllCallback BeforeEachCallback BeforeTestExecutionCallback ParameterResolver TestExecutionExceptionHandler AfterTestExecutionCallback AfterEachCallback AfterAllCallback Note how they correspond closely to the testing lifecycle Of these only BeforeTestExecutionCallback and AfterTestExecutionCallback are new They are more of a technical requirement in case an extension needs to run as closely to the test as possible for example to benchmark a test What exactly is an extension and how does it interact with extension points For each of the extension points there exists a Java interface that has the same name The interfaces are quite simple and usually have one sometimes two methods At each point JUnit gathers a lot of context information Ill get to that shortly accesses a list of registered extensions that implement the corresponding interface calls the methods and changes the tests behavior according to what is returned by the methods A Simple Benchmark Before diving deeper lets look at a simple example Lets say I want to benchmark my tests which for this example means Ill print elapsed time to the console As youd expect before test execution I store the test launch time and after execution I print the elapsed time Looking over the list of extension points two stand out as being useful BeforeTestExecutionCallback and AfterTestExecutionCallback Here are their definitions public interface BeforeTestExecutionCallback extends Extension void beforeTestExecution TestExtensionContext context throws Exception public interface AfterTestExecutionCallback extends Extension void afterTestExecution
You must have JavaScript enabled to view digital editions.