Java Magazine, Nov/Dec 2016
ORACLE COM JAVAMAGAZINE NOVEMBER DECEMBER 2016 32 junit 5 As you can see the new methods use the store instead of the field to persist and access the extensions state Retrofitting @ Test Lets look at a new example that leverages much of the material Ive just covered Lets say I want to move from JUnit 4 to JUnit 5 First of all thanks to the design of the new architecture it is straightforward to run old and new tests side by side This means it is not necessary to migrate individual tests which makes what follows a little moot but no less fun I want to replace JUnit 4 s @ Test annotation with a new version that makes the annotated method a JUnit 5 test I could pick JUnit 5 s @ Test and this works in most cases a simple search and replace on the import would do the trick Note This is just a thought experiment not an actual recommendation But JUnit 4 s optional arguments expected to fail tests when a particular exception is not thrown and timeout to fail tests that run too long are not supported in JUnit 5 s annotation JUnit 5 provides these features via assertThrows and the upcoming assertTimeout But Im looking for a way that requires no manual intervention which precludes updating the tests to the new API So why not create my own @ Test that JUnit 5 will recognize and run and that implements the desired functionality First things first Ill declare a new @ Test annotation @ Target METHOD @ Retention RetentionPolicy RUNTIME @ org junit jupiter api Test public @ interface Test This is pretty straightforward I just declare the annotation and meta annotate it with JUnit 5 s @ Test so JUnit will identify annotated methods as test methods and run them Expecting exceptions To manage expected exceptions I first need a way for the user to declare them For this I extend my annotation with code that is heavily inspired by JUnit 4 s implementation of this feature public @ interface Test class None extends Throwable private static final long serialVersionUID 1L private None Class extends Throwable expected default None class Now a user can use expected to specify which exception to expect It defaults to None The extension itself will be found in a class called ExpectedExceptionExtension which is shown below To register it with JUnit I annotate @ Test with @ ExtendWith Expected ExceptionExtension class Next I need to actually implement the desired behavior Here is a short description of how I can do it 1 If a test throws an exception check whether it is the expected exception If it is store the fact that the expected exception was thrown Otherwise store that it was the wrong one and rethrow the exception because During the test lifecycle JUnit pauses at each extension point searches for all extensions that apply to the current test node gathers context information and calls extensions in outside in order
You must have JavaScript enabled to view digital editions.