JUnit Jupiter comes with many of the assertion methods that JUnit 4 already has and added a few more so that it may support Java 8 lambdas. Also in this library, assertions are present for all primitive types, Objects, and arrays (either of primitives or Objects). The assertions are a collection of utility methods that support asserting conditions in tests.
Assertions help us to validate the expected output with the actual output of test cases.
All JUnit Jupiter assertions methods are static and present in the org.junit.jupiter.api.Assertions class.
Junit 5 Assertions
You will get below list of Assert methods(static methods and present in the org.junit.jupiter.api.Assertions class) are avialabe in Junit 5with Overloaded versions:
assertTrue
assertFalse
assertEquals
assertNotEquals
assertNull
assertNotNull
assertSame
assertNotSame
assertArrayEquals
assertAll
assertThrows
assertDoesNotThrow
assertIterableEquals
assertTimeout
assertTimeoutPreemptively
assertLinesMatch
fail
Let’s understand these assert methods using a below demo project.
pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.kkjavatutorials</groupId> <artifactId>JUnit5AssertionsExample</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <maven.compiler.target>8</maven.compiler.target> <maven.compiler.source>8</maven.compiler.source> <junit.jupiter.version>5.6.2</junit.jupiter.version> </properties> <dependencies> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>${junit.jupiter.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>${junit.jupiter.version}</version> <scope>test</scope> </dependency> </dependencies> </project> |
Classes for that Junit test cases written:
Employee.java
MyUtils.java
Employee.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.kkjavatutorials; public class Employee { private String firstName; private String lastName; public Employee(String firstName, String lastName) { super(); this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } } |
MyUtils.java
1 2 3 4 5 6 7 8 |
package com.kkjavatutorials; public class MyUtils { public int add(int n1, int n2) { return n1+n2; } } |
Test class JUnit5Assertions.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 |
package com.kkjavatutorials; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertIterableEquals; import static org.junit.jupiter.api.Assertions.assertLinesMatch; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTimeout; import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.function.BooleanSupplier; import org.junit.jupiter.api.Test; /** * @author KK JavaTutorials * JUnit 5 Annotation Examples */ public class JUnit5Assertions { /** * Using assertTrue assertion, it is possible to verify/test the supplied conditions are true */ @Test void assertTrueTest() { assertTrue(10 > 6, "10 is greater the 6"); //assertTrue(10 > 6,()->"10 is greater the 6"); } /** * Using assertFalse assertion, it is possible to verify/test the supplied conditions are false */ @Test void assertFalseTest() { BooleanSupplier condition = () -> 78 > 120; assertFalse(condition, "78 is not greater then 120"); } /** * In case you want to assert that two int values are equals, we can use the assertEquals assertion. */ @Test void assertEqualsTest1() { MyUtils myUtils = new MyUtils(); int actual = myUtils.add(14, 6); assertEquals(20, actual); } /** * If You want to assert that the actual value differs by a predefined delta from the * expected value then we can still use the assertEquals but we have to pass the delta * value as the third parameter. */ @Test void assertEqualsTest2() { float square = 4 * 4; float rectangle = 5 * 4; float delta = 4; assertEquals(square, rectangle, delta); } /** *You can use assertNotEquals assertion when expected and the actual values are not equal. */ @Test void assertNotEqualsTest() { // result of an algorithm Integer value = 100; assertNotEquals(10, value, "The result cannot be 100"); } /** * When you want to assert that an object is not null then you can use the assertNotNull assertion. *Here good Thing is that the failure message will be retrieved in a lazy way since it's a Supplier. */ @Test void assertNotNullTest() { Object obj = new Object(); assertNotNull(obj, () -> "The object should not be null"); } /** * you can use the assertNull assertion to check if the actual is null * Here good Thing is that the failure message will be retrieved in a lazy way since it's a Supplier. */ @Test void assertNullTest() { Object obj = null; assertNull(obj, () -> "The object should be null"); } /** * When you want to assert that the expected and the actual result refer to the same Object then * you must use the assertSame assertion */ @Test void assertSameTest() { String language = "C++"; Optional<String> optional = Optional.of(language); assertSame(language, optional.get()); } /** * When you want to assert that the expected and the actual result not refer to the same Object then * you must use the assertNotSame assertion */ @Test void assertNotSameTest() { String language = "C++"; Optional<String> optional = Optional.of(language); language = "Java"; assertNotSame(language, optional.get()); } /** * You can use assertArrayEquals assertion to verify that the expected and actual arrays are equals. * If the arrays are not equal then the message "Both Arrays should be equal" will be displayed as output. */ @Test void assertArrayEqualsTest() { char[] expected = { 'J', 'a', 'v', 'a'}; char[] actual = "Java".toCharArray(); assertArrayEquals(expected, actual, "Both Arrays should be equal"); } /** * assertAll assertion allows the creation of grouped assertions, where all the assertions are * executed and their failures are reported together. * The point to be noted here that the execution of a grouped assertion is interrupted only when * one of the executables throws an exception */ @Test void assertAllTest() { Employee employee = new Employee("Sean", "Murphy"); assertAll( "employeeInfo", () -> assertNotNull(employee.getFirstName(), ()->"First Name Should not be null"), () -> assertNotNull("murphy", employee.getLastName().toLowerCase()) ); } /** * assertThrows assertion allows us to assert if an executable * throws the specified exception type. * This assertion will be failed if no exception is thrown or if an exception * of a different type is thrown */ @Test void assertThrowsTest() { Throwable exception = assertThrows( IllegalArgumentException.class, () -> { throw new IllegalArgumentException("Your Exception message"); } ); assertEquals("Your Exception message", exception.getMessage()); } /** * This assertion assert that execution of the supplied executable does not throw any kind of exception. */ @Test void assertDoesNotThrowTest() { String input = "25.24E+8"; assertDoesNotThrow(() -> Double.parseDouble(input),"String not able to parse into double"); } /** * The assertIterableEquals assertion use to compare that the expected and the actual iterables are deeply equal. * both iterable must return equal elements in the same order and it is not required that the two * iterables are of the same type in order to compare */ @Test public void assertIterableEqualsTest() { Iterable<String> list1 = new ArrayList<>(Arrays.asList("KK", "PK", "MK")); Iterable<String> liat2 = new LinkedList<>(Arrays.asList("KK", "PK", "MK")); assertIterableEquals(list1, liat2); } /** * In case you want to assert that the execution of a supplied Executable ends before a * specified Timeout then you can use the assertTimeout assertion. * Using this assertion the supplied executable will be executed in the same * thread of the calling code. You should note that execution of the supplier won't be preemptively * aborted if the timeout is exceeded. *In case you want to be sure that execution of the executable will be aborted once it *exceeded the timeout,you can use the assertTimeoutPreemptively assertion. */ @Test void assertTimeoutTest() { assertTimeout( Duration.ofMillis(500), () -> { //code that requires less then 500 MillisSeconds to execute Thread.sleep(400); } ); } /** * In case of assertTimeoutPreemptively() execution of the Executable or ThrowingSupplier * can be preemptively aborted if the timeout is exceeded by specified limit. In case of assertTimeout() * Executable or ThrowingSupplier will NOT be aborted. */ @Test void assertTimeoutPreemptivelyTest() { assertTimeoutPreemptively(Duration.ofMillis(500), () -> { Thread.sleep(400); return "Final Result"; }); } /** * The assertLinesMatch assertion is used to compare the expected list of String matches the actual list. * * This assertion differs from the assertEquals and assertIterableEquals since, for each pair of expected * and actual lines, it performs below algorithm: * 1.check if the expected line is equal to the actual one. If yes it continues with the next pair * 2.treat the expected line as a regular expression and performs a check with the String.matches() method. If yes * it continues with the next pair * 3.check if the expected line is a fast-forward marker. If yes then apply fast-forward and repeat the algorithm from the step 1 * */ @Test void assertLinesMatchTest() { List<String> expected = Arrays.asList("Scala", "\\d+", "Java"); List<String> actual = Arrays.asList("Scala", "34", "Java"); assertLinesMatch(expected, actual); } /** * The fail assertion fails a test case with the provided failure message as well as the underlying * cause. This can be useful to mark a test when it's development it's not completed: */ @Test void failTest() { //Test not completed yet //fail("Test not completed yet!!"); } } |
The output of the above project:
You May Also Like:
Junit 5 Architecture
JUnit 5 Annotations
JUnit 5 Maven Dependency
JUnit 5 with Gradle Dependency
JUnit 5 Test Lifecycle
JUnit 5 @BeforeAll annotation example
Unit 5 @AfterAll annotation example
JUnit 5 @BeforeEach and @AfterEach annotation Example
JUnit 5 Display Names
That’s all about Assertions in JUnit 5
If you have any feedback or suggestion please feel free to drop in below comment box.