0
# Assertions and Assumptions
1
2
Comprehensive assertion methods for verifying test conditions and assumptions for conditional test execution. JUnit Jupiter provides a rich set of assertion methods with clear failure messages and support for custom error messages.
3
4
## Imports
5
6
```java
7
import static org.junit.jupiter.api.Assertions.*;
8
import static org.junit.jupiter.api.Assumptions.*;
9
```
10
11
## Capabilities
12
13
### Basic Assertions
14
15
Core assertion methods for common verification scenarios.
16
17
```java { .api }
18
/**
19
* Assert that two objects are equal
20
*/
21
static void assertEquals(Object expected, Object actual);
22
static void assertEquals(Object expected, Object actual, String message);
23
static void assertEquals(Object expected, Object actual, Supplier<String> messageSupplier);
24
25
/**
26
* Assert that two objects are not equal
27
*/
28
static void assertNotEquals(Object unexpected, Object actual);
29
static void assertNotEquals(Object unexpected, Object actual, String message);
30
static void assertNotEquals(Object unexpected, Object actual, Supplier<String> messageSupplier);
31
32
/**
33
* Assert that a condition is true
34
*/
35
static void assertTrue(boolean condition);
36
static void assertTrue(boolean condition, String message);
37
static void assertTrue(boolean condition, Supplier<String> messageSupplier);
38
39
/**
40
* Assert that a condition is false
41
*/
42
static void assertFalse(boolean condition);
43
static void assertFalse(boolean condition, String message);
44
static void assertFalse(boolean condition, Supplier<String> messageSupplier);
45
46
/**
47
* Assert that an object is null
48
*/
49
static void assertNull(Object actual);
50
static void assertNull(Object actual, String message);
51
static void assertNull(Object actual, Supplier<String> messageSupplier);
52
53
/**
54
* Assert that an object is not null
55
*/
56
static void assertNotNull(Object actual);
57
static void assertNotNull(Object actual, String message);
58
static void assertNotNull(Object actual, Supplier<String> messageSupplier);
59
```
60
61
**Usage Examples:**
62
63
```java
64
@Test
65
void testBasicAssertions() {
66
assertEquals(4, 2 + 2, "Simple addition should work");
67
assertNotEquals(3, 2 + 2);
68
assertTrue(5 > 3, "5 should be greater than 3");
69
assertFalse(5 < 3);
70
71
String nullString = null;
72
String nonNullString = "hello";
73
assertNull(nullString);
74
assertNotNull(nonNullString, "String should not be null");
75
}
76
```
77
78
### Reference Assertions
79
80
Assert object identity and reference equality.
81
82
```java { .api }
83
/**
84
* Assert that two objects refer to the same object
85
*/
86
static void assertSame(Object expected, Object actual);
87
static void assertSame(Object expected, Object actual, String message);
88
static void assertSame(Object expected, Object actual, Supplier<String> messageSupplier);
89
90
/**
91
* Assert that two objects do not refer to the same object
92
*/
93
static void assertNotSame(Object unexpected, Object actual);
94
static void assertNotSame(Object unexpected, Object actual, String message);
95
static void assertNotSame(Object unexpected, Object actual, Supplier<String> messageSupplier);
96
```
97
98
**Usage Example:**
99
100
```java
101
@Test
102
void testReferenceAssertions() {
103
String str1 = new String("hello");
104
String str2 = new String("hello");
105
String str3 = str1;
106
107
assertEquals(str1, str2); // Content equality
108
assertNotSame(str1, str2, "Different objects should not be same");
109
assertSame(str1, str3, "Same reference should be same");
110
}
111
```
112
113
### Array and Collection Assertions
114
115
Specialized assertions for arrays and collections.
116
117
```java { .api }
118
/**
119
* Assert that two arrays are equal
120
*/
121
static void assertArrayEquals(boolean[] expected, boolean[] actual);
122
static void assertArrayEquals(byte[] expected, byte[] actual);
123
static void assertArrayEquals(char[] expected, char[] actual);
124
static void assertArrayEquals(double[] expected, double[] actual);
125
static void assertArrayEquals(double[] expected, double[] actual, double delta);
126
static void assertArrayEquals(float[] expected, float[] actual);
127
static void assertArrayEquals(float[] expected, float[] actual, double delta);
128
static void assertArrayEquals(int[] expected, int[] actual);
129
static void assertArrayEquals(long[] expected, long[] actual);
130
static void assertArrayEquals(Object[] expected, Object[] actual);
131
static void assertArrayEquals(short[] expected, short[] actual);
132
133
/**
134
* Assert that two iterables are equal
135
*/
136
static void assertIterableEquals(Iterable<?> expected, Iterable<?> actual);
137
static void assertIterableEquals(Iterable<?> expected, Iterable<?> actual, String message);
138
static void assertIterableEquals(Iterable<?> expected, Iterable<?> actual, Supplier<String> messageSupplier);
139
140
/**
141
* Assert that lines match with pattern support
142
*/
143
static void assertLinesMatch(List<String> expectedLines, List<String> actualLines);
144
static void assertLinesMatch(List<String> expectedLines, List<String> actualLines, String message);
145
static void assertLinesMatch(List<String> expectedLines, List<String> actualLines, Supplier<String> messageSupplier);
146
static void assertLinesMatch(Stream<String> expectedLines, Stream<String> actualLines);
147
static void assertLinesMatch(Stream<String> expectedLines, Stream<String> actualLines, String message);
148
static void assertLinesMatch(Stream<String> expectedLines, Stream<String> actualLines, Supplier<String> messageSupplier);
149
```
150
151
**Usage Examples:**
152
153
```java
154
@Test
155
void testArrayAssertions() {
156
int[] expected = {1, 2, 3};
157
int[] actual = {1, 2, 3};
158
assertArrayEquals(expected, actual);
159
160
double[] expectedDoubles = {1.1, 2.2, 3.3};
161
double[] actualDoubles = {1.1, 2.2, 3.3};
162
assertArrayEquals(expectedDoubles, actualDoubles, 0.01);
163
}
164
165
@Test
166
void testIterableAssertions() {
167
List<String> expected = Arrays.asList("a", "b", "c");
168
List<String> actual = Arrays.asList("a", "b", "c");
169
assertIterableEquals(expected, actual);
170
}
171
172
@Test
173
void testLinesMatch() {
174
List<String> expected = Arrays.asList("Hello.*", "\\d+", "End");
175
List<String> actual = Arrays.asList("Hello World", "123", "End");
176
assertLinesMatch(expected, actual);
177
}
178
```
179
180
### Exception Assertions
181
182
Assert that specific exceptions are thrown or not thrown.
183
184
```java { .api }
185
/**
186
* Assert that executable throws expected exception type
187
*/
188
static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executable);
189
static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executable, String message);
190
static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executable, Supplier<String> messageSupplier);
191
192
/**
193
* Assert that executable throws exactly the expected exception type
194
*/
195
static <T extends Throwable> T assertThrowsExactly(Class<T> expectedType, Executable executable);
196
static <T extends Throwable> T assertThrowsExactly(Class<T> expectedType, Executable executable, String message);
197
static <T extends Throwable> T assertThrowsExactly(Class<T> expectedType, Executable executable, Supplier<String> messageSupplier);
198
199
/**
200
* Assert that executable does not throw any exception
201
*/
202
static void assertDoesNotThrow(Executable executable);
203
static void assertDoesNotThrow(Executable executable, String message);
204
static void assertDoesNotThrow(Executable executable, Supplier<String> messageSupplier);
205
static <T> T assertDoesNotThrow(ThrowingSupplier<T> supplier);
206
static <T> T assertDoesNotThrow(ThrowingSupplier<T> supplier, String message);
207
static <T> T assertDoesNotThrow(ThrowingSupplier<T> supplier, Supplier<String> messageSupplier);
208
```
209
210
**Usage Examples:**
211
212
```java
213
@Test
214
void testExceptionAssertions() {
215
// Assert specific exception is thrown
216
IllegalArgumentException exception = assertThrows(
217
IllegalArgumentException.class,
218
() -> { throw new IllegalArgumentException("Invalid argument"); },
219
"Should throw IllegalArgumentException"
220
);
221
assertEquals("Invalid argument", exception.getMessage());
222
223
// Assert exact exception type
224
RuntimeException exactException = assertThrowsExactly(
225
RuntimeException.class,
226
() -> { throw new RuntimeException("Runtime error"); }
227
);
228
229
// Assert no exception is thrown
230
assertDoesNotThrow(() -> {
231
String result = "safe operation";
232
return result;
233
});
234
235
// Assert no exception and return value
236
String result = assertDoesNotThrow(() -> "safe operation");
237
assertEquals("safe operation", result);
238
}
239
```
240
241
### Timeout Assertions
242
243
Assert that operations complete within specified time limits.
244
245
```java { .api }
246
/**
247
* Assert that executable completes within timeout
248
*/
249
static void assertTimeout(Duration timeout, Executable executable);
250
static void assertTimeout(Duration timeout, Executable executable, String message);
251
static void assertTimeout(Duration timeout, Executable executable, Supplier<String> messageSupplier);
252
static <T> T assertTimeout(Duration timeout, ThrowingSupplier<T> supplier);
253
static <T> T assertTimeout(Duration timeout, ThrowingSupplier<T> supplier, String message);
254
static <T> T assertTimeout(Duration timeout, ThrowingSupplier<T> supplier, Supplier<String> messageSupplier);
255
256
/**
257
* Assert that executable completes within timeout, preemptively aborting if it takes too long
258
*/
259
static void assertTimeoutPreemptively(Duration timeout, Executable executable);
260
static void assertTimeoutPreemptively(Duration timeout, Executable executable, String message);
261
static void assertTimeoutPreemptively(Duration timeout, Executable executable, Supplier<String> messageSupplier);
262
static <T> T assertTimeoutPreemptively(Duration timeout, ThrowingSupplier<T> supplier);
263
static <T> T assertTimeoutPreemptively(Duration timeout, ThrowingSupplier<T> supplier, String message);
264
static <T> T assertTimeoutPreemptively(Duration timeout, ThrowingSupplier<T> supplier, Supplier<String> messageSupplier);
265
```
266
267
**Usage Examples:**
268
269
```java
270
@Test
271
void testTimeoutAssertions() {
272
// Assert operation completes within timeout
273
assertTimeout(Duration.ofSeconds(2), () -> {
274
Thread.sleep(1000); // 1 second delay
275
});
276
277
// Assert with return value
278
String result = assertTimeout(Duration.ofSeconds(1), () -> {
279
return "Quick operation";
280
});
281
assertEquals("Quick operation", result);
282
283
// Preemptive timeout (interrupts if takes too long)
284
assertTimeoutPreemptively(Duration.ofMillis(500), () -> {
285
Thread.sleep(100); // Short delay
286
});
287
}
288
```
289
290
### Instance Type Assertions
291
292
Assert object types and inheritance relationships.
293
294
```java { .api }
295
/**
296
* Assert that object is instance of expected type
297
*/
298
static void assertInstanceOf(Class<?> expectedType, Object actualValue);
299
static void assertInstanceOf(Class<?> expectedType, Object actualValue, String message);
300
static void assertInstanceOf(Class<?> expectedType, Object actualValue, Supplier<String> messageSupplier);
301
static <T> T assertInstanceOf(Class<T> expectedType, Object actualValue);
302
static <T> T assertInstanceOf(Class<T> expectedType, Object actualValue, String message);
303
static <T> T assertInstanceOf(Class<T> expectedType, Object actualValue, Supplier<String> messageSupplier);
304
```
305
306
**Usage Example:**
307
308
```java
309
@Test
310
void testInstanceAssertions() {
311
Object obj = "Hello World";
312
313
// Simple instance check
314
assertInstanceOf(String.class, obj);
315
316
// With type casting
317
String str = assertInstanceOf(String.class, obj, "Object should be String");
318
assertEquals(11, str.length());
319
320
// Check inheritance
321
Number num = 42;
322
assertInstanceOf(Integer.class, num);
323
}
324
```
325
326
### Grouped Assertions
327
328
Execute multiple assertions together and report all failures.
329
330
```java { .api }
331
/**
332
* Group multiple assertions and execute all, reporting all failures
333
*/
334
static void assertAll(Executable... executables);
335
static void assertAll(String heading, Executable... executables);
336
static void assertAll(Collection<Executable> executables);
337
static void assertAll(String heading, Collection<Executable> executables);
338
static void assertAll(Stream<Executable> executables);
339
static void assertAll(String heading, Stream<Executable> executables);
340
```
341
342
**Usage Example:**
343
344
```java
345
@Test
346
void testGroupedAssertions() {
347
Person person = new Person("John", "Doe", 30);
348
349
assertAll("Person properties",
350
() -> assertEquals("John", person.getFirstName()),
351
() -> assertEquals("Doe", person.getLastName()),
352
() -> assertTrue(person.getAge() > 0),
353
() -> assertNotNull(person.getFullName())
354
);
355
356
// Using collections
357
List<Executable> assertions = Arrays.asList(
358
() -> assertEquals(4, 2 + 2),
359
() -> assertTrue(5 > 3),
360
() -> assertNotNull("test")
361
);
362
assertAll("Math assertions", assertions);
363
}
364
```
365
366
### Failure Methods
367
368
Explicitly fail tests with custom messages.
369
370
```java { .api }
371
/**
372
* Explicitly fail test
373
*/
374
static void fail();
375
static void fail(String message);
376
static void fail(String message, Throwable cause);
377
static void fail(Throwable cause);
378
static void fail(Supplier<String> messageSupplier);
379
static <T> T fail();
380
static <T> T fail(String message);
381
static <T> T fail(String message, Throwable cause);
382
static <T> T fail(Throwable cause);
383
static <T> T fail(Supplier<String> messageSupplier);
384
```
385
386
**Usage Example:**
387
388
```java
389
@Test
390
void testFailMethods() {
391
boolean condition = false;
392
393
if (!condition) {
394
fail("Condition was not met");
395
}
396
397
// With supplier for expensive message creation
398
if (!condition) {
399
fail(() -> "Complex message: " + generateComplexMessage());
400
}
401
402
// In switch statement
403
switch (value) {
404
case 1: /* handle */ break;
405
case 2: /* handle */ break;
406
default: fail("Unexpected value: " + value);
407
}
408
}
409
```
410
411
### Assumptions
412
413
Conditional test execution based on assumptions about the test environment.
414
415
```java { .api }
416
/**
417
* Assume that a condition is true, abort test if false
418
*/
419
static void assumeTrue(boolean assumption);
420
static void assumeTrue(boolean assumption, String message);
421
static void assumeTrue(boolean assumption, Supplier<String> messageSupplier);
422
static void assumeTrue(BooleanSupplier assumptionSupplier);
423
static void assumeTrue(BooleanSupplier assumptionSupplier, String message);
424
static void assumeTrue(BooleanSupplier assumptionSupplier, Supplier<String> messageSupplier);
425
426
/**
427
* Assume that a condition is false, abort test if true
428
*/
429
static void assumeFalse(boolean assumption);
430
static void assumeFalse(boolean assumption, String message);
431
static void assumeFalse(boolean assumption, Supplier<String> messageSupplier);
432
static void assumeFalse(BooleanSupplier assumptionSupplier);
433
static void assumeFalse(BooleanSupplier assumptionSupplier, String message);
434
static void assumeFalse(BooleanSupplier assumptionSupplier, Supplier<String> messageSupplier);
435
436
/**
437
* Execute test code only if assumption is true
438
*/
439
static void assumingThat(boolean assumption, Executable executable);
440
static void assumingThat(BooleanSupplier assumptionSupplier, Executable executable);
441
```
442
443
**Usage Examples:**
444
445
```java
446
@Test
447
void testOnlyOnLinux() {
448
assumeTrue(System.getProperty("os.name").toLowerCase().contains("linux"));
449
450
// This test will only run on Linux
451
// Will be skipped (not failed) on other operating systems
452
assertEquals("/", File.separator);
453
}
454
455
@Test
456
void testWithPartialAssumption() {
457
// This part always runs
458
assertEquals(4, 2 + 2);
459
460
// This part only runs if assumption is true
461
assumingThat(System.getProperty("env").equals("dev"), () -> {
462
// Development-only test code
463
assertEquals("localhost", getServerHost());
464
});
465
466
// This part always runs
467
assertTrue(true);
468
}
469
470
@Test
471
void testWithEnvironmentCheck() {
472
String env = System.getProperty("test.env");
473
assumeFalse("prod".equals(env), "Not running destructive test in production");
474
475
// Destructive test that should not run in production
476
database.deleteAllData();
477
}
478
```
479
480
### Assertion Failure Builder
481
482
Build custom assertion failures with detailed information.
483
484
```java { .api }
485
class AssertionFailureBuilder {
486
/**
487
* Create new assertion failure builder
488
*/
489
static AssertionFailureBuilder assertionFailure();
490
491
/**
492
* Set failure message
493
*/
494
AssertionFailureBuilder message(String message);
495
496
/**
497
* Set expected value
498
*/
499
AssertionFailureBuilder expected(Object expected);
500
501
/**
502
* Set actual value
503
*/
504
AssertionFailureBuilder actual(Object actual);
505
506
/**
507
* Set cause exception
508
*/
509
AssertionFailureBuilder cause(Throwable cause);
510
511
/**
512
* Build the assertion failure
513
*/
514
AssertionFailedError build();
515
}
516
```
517
518
**Usage Example:**
519
520
```java
521
@Test
522
void testCustomAssertion() {
523
String expected = "hello";
524
String actual = "world";
525
526
if (!expected.equals(actual)) {
527
throw AssertionFailureBuilder.assertionFailure()
528
.message("Strings should match")
529
.expected(expected)
530
.actual(actual)
531
.build();
532
}
533
}
534
```