Java Magazine, Nov/Dec 2016
ORACLE COM JAVAMAGAZINE NOVEMBER DECEMBER 2016 17 junit 5 @ Test void assertionShouldBeTrueWithLambda assertEquals 3 2 true 3 not equal to 2 The org junit jupiter api Assumptions class provides assumeTrue assumeFalse and assumingThat static methods As stated in the documentation these methods are useful for stating assumptions about the conditions in which a test is meaningful If an assumption fails it does not mean the code is broken but only that the test provides no useful information The default JUnit runner ignores such failing tests This approach enables other tests in the series to be executed Grouping Assertions Its also possible to group a list of assertions together Using the assertAll static method shown in Listing 7 causes all assertions to be executed together and all failures to be reported together Listing 7 class GroupedAssertionsTest @ Test void groupedAssertionsAreValid assertAll assertTrue true assertFalse false Expecting the Unexpected JUnit 4 provides a way to handle exceptions by declaring them as an attribute to the @ Test annotation This is an enhancement compared with previous versions that required the use of try catch blocks for handling exceptions JUnit 5 introduces the usage of lambda expressions for defining the exception inside the assertion statement Listing 8 shows the placement of the exception directly into the assertion Listing 8 class ExceptionsTest @ Test void expectingArithmeticException assertThrows ArithmeticException class divideByZero int divideByZero return 3 0 With JUnit 5 its also possible to assign the exception to a variable in order to assert conditions on its values as shown in Listing 9 Listing 9 class Exceptions2Test @ Test void expectingArithmeticException StringIndexOutOfBoundsException exception expectThrows StringIndexOutOfBoundsException class JUnit5 Rocks substring 1 assertEquals exception getMessage
You must have JavaScript enabled to view digital editions.