Java Magazine, Nov/Dec 2016
ORACLE COM JAVAMAGAZINE NOVEMBER DECEMBER 2016 16 junit 5 @ BeforeEach will be executed before each @ Test method and the method annotated with @ AfterEach will be executed after each @ Test method The methods annotated with @ BeforeAll and @ AfterAll will be executed before and after the execution of all @ Test methods These four annotations are applied to the @ Test methods of the class in which they reside and they will also be applied to the class hierarchy if any exists Test hierarchies are discussed next The methods annotated with @ BeforeAll and @ AfterAll need to be defined as static @ Nested test hierarchies JUnit 5 supports creating hierarchies of test classes by nesting them inside each other This option enables you to group tests logically and have them under the same parent which facilitates applying the same initialization methods for each test Listing 5 shows an example of using test hierarchies Listing 5 class NestedTest private Queue String items @ BeforeEach void setup items new LinkedList @ Test void isEmpty assertTrue items isEmpty @ Nested class WhenEmpty @ Test public void removeShouldThrowException expectThrows NoSuchElementException class items remove @ Nested class WhenWithOneElement @ Test void addingOneElementShouldIncreaseSize items add Item assertEquals items size 1 Assertions and Assumptions The org junit jupiter api Assertions class of JUnit 5 contains static assertion methods such as assertEquals assertTrue assertNull and assertSame and their corresponding negative versions for handling the conditions in test methods JUnit 5 leverages the use of lambda expressions with these assertion methods by providing overloaded versions that take an instance of java util function Supplier This enables the evaluation of the assertion message lazily meaning that potentially complex calculations are delayed until a failed assertion Listing 6 shows using a lambda expression in an assertion Listing 6 class AssertionsTest @ Test void assertionShouldBeTrue assertEquals 2 2 true
You must have JavaScript enabled to view digital editions.