0
# Assertions
1
2
The `Assert` class provides static methods for verifying expected behavior in tests. When an assertion fails, it throws an `AssertionError` causing the test to fail. All assertion methods are available with and without an optional message parameter that describes the assertion.
3
4
## Capabilities
5
6
### Equality Assertions
7
8
Verify that two values are equal using the `equals()` method. Supports all object types and primitives with specialized overloads for better failure messages.
9
10
```java { .api }
11
/**
12
* Asserts that two objects are equal
13
* @param message - Optional message to display on failure
14
* @param expected - Expected value
15
* @param actual - Actual value
16
*/
17
public static void assertEquals(String message, Object expected, Object actual);
18
public static void assertEquals(Object expected, Object actual);
19
20
// Primitive overloads for better error messages
21
public static void assertEquals(String message, long expected, long actual);
22
public static void assertEquals(long expected, long actual);
23
public static void assertEquals(String message, double expected, double actual, double delta);
24
public static void assertEquals(double expected, double actual, double delta);
25
public static void assertEquals(String message, float expected, float actual, float delta);
26
public static void assertEquals(float expected, float actual, float delta);
27
```
28
29
**Usage Examples:**
30
31
```java
32
import org.junit.Test;
33
import static org.junit.Assert.*;
34
35
public class EqualityTest {
36
@Test
37
public void testBasicEquality() {
38
assertEquals(4, 2 + 2);
39
assertEquals("hello", "hel" + "lo");
40
assertEquals(100L, 100L);
41
}
42
43
@Test
44
public void testWithMessage() {
45
assertEquals("Addition should work", 10, 5 + 5);
46
}
47
48
@Test
49
public void testFloatingPoint() {
50
// For floating point, provide delta for precision
51
assertEquals(0.33, 1.0 / 3.0, 0.01);
52
assertEquals("Pi approximation", 3.14, Math.PI, 0.01);
53
}
54
55
@Test
56
public void testObjects() {
57
Person expected = new Person("Alice", 30);
58
Person actual = new Person("Alice", 30);
59
assertEquals(expected, actual); // Uses Person.equals()
60
}
61
}
62
```
63
64
### Inequality Assertions
65
66
Verify that two values are not equal. Added in JUnit 4.11 to complement `assertEquals`.
67
68
```java { .api }
69
/**
70
* Asserts that two objects are not equal
71
* @param message - Optional message to display on failure
72
* @param unexpected - Value that should not match
73
* @param actual - Actual value
74
*/
75
public static void assertNotEquals(String message, Object unexpected, Object actual);
76
public static void assertNotEquals(Object unexpected, Object actual);
77
78
// Primitive overloads
79
public static void assertNotEquals(String message, long unexpected, long actual);
80
public static void assertNotEquals(long unexpected, long actual);
81
public static void assertNotEquals(String message, double unexpected, double actual, double delta);
82
public static void assertNotEquals(double unexpected, double actual, double delta);
83
public static void assertNotEquals(String message, float unexpected, float actual, float delta);
84
public static void assertNotEquals(float unexpected, float actual, float delta);
85
```
86
87
**Usage Examples:**
88
89
```java
90
import org.junit.Test;
91
import static org.junit.Assert.*;
92
93
public class InequalityTest {
94
@Test
95
public void testNotEqual() {
96
assertNotEquals(5, 2 + 2);
97
assertNotEquals("Different strings", "hello", "world");
98
}
99
100
@Test
101
public void testFloatingPointNotEqual() {
102
assertNotEquals(0.5, 1.0 / 3.0, 0.01);
103
}
104
}
105
```
106
107
### Boolean Assertions
108
109
Verify boolean conditions. The most commonly used assertions in unit testing.
110
111
```java { .api }
112
/**
113
* Asserts that a condition is true
114
* @param message - Optional message to display on failure
115
* @param condition - Condition to check
116
*/
117
public static void assertTrue(String message, boolean condition);
118
public static void assertTrue(boolean condition);
119
120
/**
121
* Asserts that a condition is false
122
* @param message - Optional message to display on failure
123
* @param condition - Condition to check
124
*/
125
public static void assertFalse(String message, boolean condition);
126
public static void assertFalse(boolean condition);
127
```
128
129
**Usage Examples:**
130
131
```java
132
import org.junit.Test;
133
import static org.junit.Assert.*;
134
135
public class BooleanTest {
136
@Test
137
public void testConditions() {
138
assertTrue(5 > 3);
139
assertFalse(5 < 3);
140
assertTrue("List should not be empty", !list.isEmpty());
141
}
142
143
@Test
144
public void testComplexConditions() {
145
List<String> items = getItems();
146
assertTrue("List should contain at least 5 items", items.size() >= 5);
147
assertFalse("List should not be empty", items.isEmpty());
148
}
149
}
150
```
151
152
### Null Assertions
153
154
Check for null and non-null values.
155
156
```java { .api }
157
/**
158
* Asserts that an object is null
159
* @param message - Optional message to display on failure
160
* @param object - Object to check
161
*/
162
public static void assertNull(String message, Object object);
163
public static void assertNull(Object object);
164
165
/**
166
* Asserts that an object is not null
167
* @param message - Optional message to display on failure
168
* @param object - Object to check
169
*/
170
public static void assertNotNull(String message, Object object);
171
public static void assertNotNull(Object object);
172
```
173
174
**Usage Examples:**
175
176
```java
177
import org.junit.Test;
178
import static org.junit.Assert.*;
179
180
public class NullTest {
181
@Test
182
public void testNullChecks() {
183
String nullString = null;
184
assertNull(nullString);
185
186
String nonNullString = "hello";
187
assertNotNull(nonNullString);
188
assertNotNull("Result should not be null", database.query());
189
}
190
191
@Test
192
public void testOptionalValue() {
193
Optional<String> result = findUser("unknown");
194
assertNotNull("Optional should not be null", result);
195
assertFalse("Optional should be empty", result.isPresent());
196
}
197
}
198
```
199
200
### Reference Assertions
201
202
Verify that two references point to the same object (using `==` instead of `equals()`).
203
204
```java { .api }
205
/**
206
* Asserts that two references point to the same object
207
* @param message - Optional message to display on failure
208
* @param expected - Expected reference
209
* @param actual - Actual reference
210
*/
211
public static void assertSame(String message, Object expected, Object actual);
212
public static void assertSame(Object expected, Object actual);
213
214
/**
215
* Asserts that two references point to different objects
216
* @param message - Optional message to display on failure
217
* @param unexpected - Reference that should not match
218
* @param actual - Actual reference
219
*/
220
public static void assertNotSame(String message, Object unexpected, Object actual);
221
public static void assertNotSame(Object unexpected, Object actual);
222
```
223
224
**Usage Examples:**
225
226
```java
227
import org.junit.Test;
228
import static org.junit.Assert.*;
229
230
public class ReferenceTest {
231
@Test
232
public void testSameReference() {
233
String str1 = "hello";
234
String str2 = str1;
235
assertSame("Should be same reference", str1, str2);
236
237
String str3 = new String("hello");
238
assertNotSame("Should be different references", str1, str3);
239
assertEquals("But should be equal", str1, str3);
240
}
241
242
@Test
243
public void testSingleton() {
244
Database db1 = Database.getInstance();
245
Database db2 = Database.getInstance();
246
assertSame("Singleton should return same instance", db1, db2);
247
}
248
}
249
```
250
251
### Array Assertions
252
253
Compare arrays element by element. Provides better error messages than comparing arrays with `assertEquals`.
254
255
```java { .api }
256
/**
257
* Asserts that two arrays are equal (same length and equal elements)
258
* @param message - Optional message to display on failure
259
* @param expecteds - Expected array
260
* @param actuals - Actual array
261
*/
262
public static void assertArrayEquals(String message, Object[] expecteds, Object[] actuals);
263
public static void assertArrayEquals(Object[] expecteds, Object[] actuals);
264
265
// Primitive array overloads
266
public static void assertArrayEquals(String message, boolean[] expecteds, boolean[] actuals);
267
public static void assertArrayEquals(boolean[] expecteds, boolean[] actuals);
268
public static void assertArrayEquals(String message, byte[] expecteds, byte[] actuals);
269
public static void assertArrayEquals(byte[] expecteds, byte[] actuals);
270
public static void assertArrayEquals(String message, char[] expecteds, char[] actuals);
271
public static void assertArrayEquals(char[] expecteds, char[] actuals);
272
public static void assertArrayEquals(String message, short[] expecteds, short[] actuals);
273
public static void assertArrayEquals(short[] expecteds, short[] actuals);
274
public static void assertArrayEquals(String message, int[] expecteds, int[] actuals);
275
public static void assertArrayEquals(int[] expecteds, int[] actuals);
276
public static void assertArrayEquals(String message, long[] expecteds, long[] actuals);
277
public static void assertArrayEquals(long[] expecteds, long[] actuals);
278
public static void assertArrayEquals(String message, double[] expecteds, double[] actuals, double delta);
279
public static void assertArrayEquals(double[] expecteds, double[] actuals, double delta);
280
public static void assertArrayEquals(String message, float[] expecteds, float[] actuals, float delta);
281
public static void assertArrayEquals(float[] expecteds, float[] actuals, float delta);
282
```
283
284
**Usage Examples:**
285
286
```java
287
import org.junit.Test;
288
import static org.junit.Assert.*;
289
290
public class ArrayTest {
291
@Test
292
public void testIntArray() {
293
int[] expected = {1, 2, 3, 4, 5};
294
int[] actual = generateSequence(5);
295
assertArrayEquals(expected, actual);
296
}
297
298
@Test
299
public void testStringArray() {
300
String[] expected = {"apple", "banana", "cherry"};
301
String[] actual = getFruits();
302
assertArrayEquals("Fruit list should match", expected, actual);
303
}
304
305
@Test
306
public void testDoubleArray() {
307
double[] expected = {1.1, 2.2, 3.3};
308
double[] actual = getValues();
309
assertArrayEquals(expected, actual, 0.01);
310
}
311
312
@Test
313
public void testByteArray() {
314
byte[] expected = {0x01, 0x02, 0x03};
315
byte[] actual = getData();
316
assertArrayEquals(expected, actual);
317
}
318
}
319
```
320
321
### Exception Assertions
322
323
Assert that code throws a specific exception type. Added in JUnit 4.13, provides better syntax than `@Test(expected=...)`.
324
325
```java { .api }
326
/**
327
* Asserts that the given runnable throws an exception of the expected type
328
* Returns the thrown exception for further assertions
329
* @param expectedThrowable - Expected exception class
330
* @param runnable - Code to execute
331
* @return The thrown exception
332
*/
333
public static <T extends Throwable> T assertThrows(
334
Class<T> expectedThrowable,
335
ThrowingRunnable runnable
336
);
337
338
/**
339
* Asserts that the given runnable throws an exception of the expected type
340
* @param message - Message to display on failure
341
* @param expectedThrowable - Expected exception class
342
* @param runnable - Code to execute
343
* @return The thrown exception
344
*/
345
public static <T extends Throwable> T assertThrows(
346
String message,
347
Class<T> expectedThrowable,
348
ThrowingRunnable runnable
349
);
350
```
351
352
**Usage Examples:**
353
354
```java
355
import org.junit.Test;
356
import static org.junit.Assert.*;
357
358
public class ExceptionTest {
359
@Test
360
public void testException() {
361
assertThrows(IllegalArgumentException.class, () -> {
362
divide(10, 0);
363
});
364
}
365
366
@Test
367
public void testExceptionWithMessage() {
368
IllegalArgumentException ex = assertThrows(
369
IllegalArgumentException.class,
370
() -> new User(-1, "Invalid")
371
);
372
assertEquals("Age must be positive", ex.getMessage());
373
}
374
375
@Test
376
public void testExceptionWithCustomMessage() {
377
assertThrows(
378
"Should throw exception for invalid input",
379
NullPointerException.class,
380
() -> processNull(null)
381
);
382
}
383
}
384
```
385
386
### Hamcrest Matcher Assertions
387
388
Assert using Hamcrest matchers for expressive, readable assertions. Requires Hamcrest library on classpath.
389
390
**Note:** These methods are deprecated as of JUnit 4.13. Use `org.hamcrest.MatcherAssert.assertThat()` instead.
391
392
```java { .api }
393
/**
394
* Asserts that actual value matches the given Hamcrest matcher
395
* @param actual - Actual value
396
* @param matcher - Hamcrest matcher
397
* @deprecated use {@code org.hamcrest.MatcherAssert.assertThat()}
398
*/
399
@Deprecated
400
public static <T> void assertThat(T actual, Matcher<? super T> matcher);
401
402
/**
403
* Asserts that actual value matches the given Hamcrest matcher
404
* @param reason - Message to display on failure
405
* @param actual - Actual value
406
* @param matcher - Hamcrest matcher
407
* @deprecated use {@code org.hamcrest.MatcherAssert.assertThat()}
408
*/
409
@Deprecated
410
public static <T> void assertThat(String reason, T actual, Matcher<? super T> matcher);
411
```
412
413
**Usage Examples:**
414
415
```java
416
import org.junit.Test;
417
import static org.junit.Assert.*;
418
import static org.hamcrest.CoreMatchers.*;
419
420
public class MatcherTest {
421
@Test
422
public void testWithMatchers() {
423
assertThat(5, is(5));
424
assertThat("hello", startsWith("hel"));
425
assertThat("world", containsString("orl"));
426
assertThat(10, not(equalTo(5)));
427
}
428
429
@Test
430
public void testCollections() {
431
List<String> items = Arrays.asList("apple", "banana", "cherry");
432
assertThat(items, hasItem("banana"));
433
assertThat(items, hasItems("apple", "cherry"));
434
assertThat(items.size(), is(3));
435
}
436
437
@Test
438
public void testWithReason() {
439
assertThat("Age should be valid", age, greaterThan(0));
440
assertThat("Name should not be empty", name, not(isEmptyString()));
441
}
442
}
443
```
444
445
### Fail
446
447
Explicitly fail a test with an optional message. Useful for marking unreachable code or creating custom validation logic.
448
449
```java { .api }
450
/**
451
* Fails a test with the given message
452
* @param message - Message explaining the failure
453
*/
454
public static void fail(String message);
455
456
/**
457
* Fails a test with no message
458
*/
459
public static void fail();
460
```
461
462
**Usage Examples:**
463
464
```java
465
import org.junit.Test;
466
import static org.junit.Assert.*;
467
468
public class FailTest {
469
@Test
470
public void testShouldNotReachHere() {
471
try {
472
methodThatShouldThrow();
473
fail("Expected exception was not thrown");
474
} catch (ExpectedException e) {
475
// Expected
476
}
477
}
478
479
@Test
480
public void testConditionalFail() {
481
Result result = performOperation();
482
if (result.hasErrors()) {
483
fail("Operation failed: " + result.getErrorMessage());
484
}
485
}
486
487
@Test
488
public void testUnimplemented() {
489
if (!isFeatureImplemented()) {
490
fail("Feature not yet implemented");
491
}
492
testFeature();
493
}
494
}
495
```
496
497
## Types
498
499
```java { .api }
500
/**
501
* Functional interface for code that may throw exceptions
502
* Used with assertThrows
503
*/
504
@FunctionalInterface
505
public interface ThrowingRunnable {
506
void run() throws Throwable;
507
}
508
509
/**
510
* Thrown when an assert equals specifically for Strings fails
511
* Provides formatted output showing differences between expected and actual
512
*/
513
public class ComparisonFailure extends AssertionError {
514
public ComparisonFailure(String message, String expected, String actual);
515
public String getExpected();
516
public String getActual();
517
public String getMessage();
518
}
519
520
/**
521
* Thrown when an assertion fails
522
*/
523
public class AssertionError extends Error {
524
public AssertionError();
525
public AssertionError(String message);
526
public AssertionError(String message, Throwable cause);
527
}
528
```
529