0
# Exceptions
1
2
Exception testing and ThrowableAssert for verifying exception types, messages, causes, and stack traces in test scenarios.
3
4
## Core Imports
5
6
```java
7
import static org.assertj.core.api.Assertions.*;
8
```
9
10
## Capabilities
11
12
### Exception Testing Methods
13
14
Methods for testing that code throws expected exceptions.
15
16
```java { .api }
17
// Primary exception testing methods
18
ThrowableAssert assertThatThrownBy(ThrowingCallable callable)
19
ThrowableTypeAssert assertThatExceptionOfType(Class<? extends Throwable> type)
20
NotThrownAssert assertThatCode(ThrowingCallable callable)
21
22
// Specific exception type shortcuts
23
ThrowableAssert assertThatIllegalArgumentException()
24
ThrowableAssert assertThatIllegalStateException()
25
ThrowableAssert assertThatIOException()
26
ThrowableAssert assertThatNullPointerException()
27
ThrowableAssert assertThatRuntimeException()
28
ThrowableAssert assertThatException()
29
30
// Failure methods
31
void fail(String reason)
32
void fail(String reason, Object... args)
33
void fail(String reason, Throwable realCause)
34
void failBecauseExceptionWasNotThrown(Class<? extends Throwable> exceptionClass)
35
```
36
37
Usage examples:
38
```java
39
// Test that exception is thrown
40
assertThatThrownBy(() -> {
41
divide(10, 0);
42
}).isInstanceOf(ArithmeticException.class)
43
.hasMessage("/ by zero");
44
45
// Test specific exception type
46
assertThatExceptionOfType(IllegalArgumentException.class)
47
.isThrownBy(() -> validateAge(-5))
48
.withMessage("Age must be positive");
49
50
// Test that no exception is thrown
51
assertThatCode(() -> {
52
validateEmail("user@domain.com");
53
}).doesNotThrowAnyException();
54
55
// Shortcut methods
56
assertThatNullPointerException()
57
.isThrownBy(() -> processNull(null))
58
.withMessage("Input cannot be null");
59
```
60
61
### ThrowableAssert Methods
62
63
Comprehensive assertions for thrown exceptions.
64
65
```java { .api }
66
ThrowableAssert assertThat(Throwable actual)
67
68
// Exception type assertions
69
ThrowableAssert isInstanceOf(Class<?> type)
70
ThrowableAssert isNotInstanceOf(Class<?> type)
71
ThrowableAssert isExactlyInstanceOf(Class<?> type)
72
ThrowableAssert isInstanceOfAny(Class<?>... types)
73
74
// Message assertions
75
ThrowableAssert hasMessage(String message)
76
ThrowableAssert hasMessage(String message, Object... args)
77
ThrowableAssert hasMessageContaining(String... values)
78
ThrowableAssert hasMessageContainingAll(String... values)
79
ThrowableAssert hasMessageStartingWith(String start)
80
ThrowableAssert hasMessageEndingWith(String end)
81
ThrowableAssert hasMessageMatching(String regex)
82
ThrowableAssert hasMessageMatching(Pattern pattern)
83
ThrowableAssert hasMessageNotContaining(String... values)
84
ThrowableAssert hasNoCause()
85
86
// Cause assertions
87
ThrowableAssert hasCause(Throwable cause)
88
ThrowableAssert hasCauseInstanceOf(Class<? extends Throwable> type)
89
ThrowableAssert hasCauseExactlyInstanceOf(Class<? extends Throwable> type)
90
ThrowableAssert hasRootCause(Throwable rootCause)
91
ThrowableAssert hasRootCauseInstanceOf(Class<? extends Throwable> type)
92
ThrowableAssert hasRootCauseExactlyInstanceOf(Class<? extends Throwable> type)
93
ThrowableAssert hasRootCauseMessage(String message)
94
95
// Stack trace assertions
96
ThrowableAssert hasStackTraceContaining(String... values)
97
ThrowableAssert hasStackTraceNotContaining(String... values)
98
99
// Suppressed exceptions
100
ThrowableAssert hasSuppressedException(Throwable suppressedException)
101
ThrowableAssert hasNoSuppressedExceptions()
102
```
103
104
Usage examples:
105
```java
106
try {
107
riskyOperation();
108
fail("Expected exception was not thrown");
109
} catch (Exception e) {
110
assertThat(e)
111
.isInstanceOf(ServiceException.class)
112
.hasMessage("Service unavailable")
113
.hasCauseInstanceOf(IOException.class)
114
.hasStackTraceContaining("ServiceImpl.process");
115
}
116
117
// Testing exception chain
118
Exception cause = new IOException("Connection failed");
119
Exception wrapper = new ServiceException("Operation failed", cause);
120
121
assertThat(wrapper)
122
.hasMessage("Operation failed")
123
.hasCause(cause)
124
.hasRootCauseInstanceOf(IOException.class)
125
.hasRootCauseMessage("Connection failed");
126
```
127
128
### ThrowableTypeAssert Methods
129
130
Type-specific exception assertions with fluent chaining.
131
132
```java { .api }
133
ThrowableTypeAssert assertThatExceptionOfType(Class<? extends Throwable> type)
134
135
// ThrowableTypeAssert methods
136
ThrowableAssert isThrownBy(ThrowingCallable callable)
137
ThrowableAssert isThrownBy(ThrowingCallable callable, String description)
138
139
// Chaining with ThrowableAssert methods
140
ThrowableAssert withMessage(String message)
141
ThrowableAssert withMessageContaining(String... values)
142
ThrowableAssert withMessageMatching(String regex)
143
ThrowableAssert withCause(Throwable cause)
144
ThrowableAssert withCauseInstanceOf(Class<? extends Throwable> type)
145
ThrowableAssert withNoCause()
146
```
147
148
Usage examples:
149
```java
150
// Type-first exception testing
151
assertThatExceptionOfType(ValidationException.class)
152
.isThrownBy(() -> validator.validate(invalidData))
153
.withMessage("Validation failed")
154
.withCauseInstanceOf(IllegalArgumentException.class);
155
156
// Multiple exception scenarios
157
assertThatExceptionOfType(TimeoutException.class)
158
.isThrownBy(() -> service.callWithTimeout(1000))
159
.withMessageContaining("timeout", "1000ms");
160
```
161
162
### NotThrownAssert Methods
163
164
Assertions for verifying that code does not throw exceptions.
165
166
```java { .api }
167
NotThrownAssert assertThatCode(ThrowingCallable callable)
168
169
// NotThrownAssert methods
170
void doesNotThrowAnyException()
171
NotThrownAssert doesNotThrowAnyExceptionOfTypes(Class<? extends Throwable>... types)
172
```
173
174
Usage examples:
175
```java
176
// Verify no exception is thrown
177
assertThatCode(() -> {
178
validService.performOperation();
179
}).doesNotThrowAnyException();
180
181
// Verify specific exception types are not thrown
182
assertThatCode(() -> {
183
safeOperation();
184
}).doesNotThrowAnyExceptionOfTypes(
185
IllegalArgumentException.class,
186
NullPointerException.class
187
);
188
```
189
190
### Custom Exception Testing
191
192
Advanced patterns for exception testing scenarios.
193
194
```java { .api }
195
// Custom ThrowingCallable for complex scenarios
196
interface ThrowingCallable {
197
void call() throws Throwable;
198
}
199
200
// Exception capture for detailed inspection
201
Throwable thrown = catchThrowable(() -> riskyCode())
202
assertThat(thrown).isInstanceOf(CustomException.class)
203
```
204
205
Usage examples:
206
```java
207
// Testing async exceptions
208
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
209
throw new RuntimeException("Async failure");
210
});
211
212
assertThatThrownBy(() -> future.get())
213
.isInstanceOf(ExecutionException.class)
214
.hasCauseInstanceOf(RuntimeException.class)
215
.hasRootCauseMessage("Async failure");
216
217
// Testing exception timing
218
long startTime = System.currentTimeMillis();
219
assertThatThrownBy(() -> {
220
Thread.sleep(100);
221
throw new TimeoutException("Too slow");
222
}).isInstanceOf(TimeoutException.class);
223
long duration = System.currentTimeMillis() - startTime;
224
assertThat(duration).isGreaterThanOrEqualTo(100);
225
226
// Capturing for multiple assertions
227
Throwable thrown = catchThrowable(() ->
228
processData(null, invalidConfig)
229
);
230
231
assertThat(thrown)
232
.isNotNull()
233
.isInstanceOf(ProcessingException.class);
234
235
// Additional assertions on the same exception
236
assertThat(thrown.getMessage())
237
.contains("configuration")
238
.contains("null");
239
```
240
241
### Exception Factory Methods
242
243
Factory methods for common exception scenarios.
244
245
```java { .api }
246
// Exception capture
247
Throwable catchThrowable(ThrowingCallable callable)
248
Exception catchException(ThrowingCallable callable)
249
RuntimeException catchRuntimeException(ThrowingCallable callable)
250
NullPointerException catchNullPointerException(ThrowingCallable callable)
251
IllegalArgumentException catchIllegalArgumentException(ThrowingCallable callable)
252
IOException catchIOException(ThrowingCallable callable)
253
254
// Throwable of specific type
255
<T extends Throwable> T catchThrowableOfType(ThrowingCallable callable, Class<T> type)
256
```
257
258
Usage examples:
259
```java
260
// Capture specific exception types
261
IOException ioException = catchIOException(() ->
262
Files.readAllLines(Paths.get("nonexistent.txt"))
263
);
264
265
assertThat(ioException)
266
.isInstanceOf(NoSuchFileException.class)
267
.hasMessageContaining("nonexistent.txt");
268
269
// Generic capture with type specification
270
CustomException custom = catchThrowableOfType(
271
() -> service.customOperation(),
272
CustomException.class
273
);
274
275
assertThat(custom)
276
.isNotNull()
277
.extracting(CustomException::getErrorCode)
278
.isEqualTo("CUSTOM_001");
279
```
280
281
### Exception Chaining and Suppression
282
283
Testing complex exception scenarios with causes and suppressed exceptions.
284
285
```java { .api }
286
// Testing exception suppression (try-with-resources)
287
ThrowableAssert hasSuppressedException(Throwable suppressedException)
288
ThrowableAssert hasNoSuppressedExceptions()
289
ThrowableAssert hasSuppressedExceptions(Throwable... suppressedExceptions)
290
291
// Testing cause chains
292
ThrowableAssert getCause()
293
ThrowableAssert getRootCause()
294
```
295
296
Usage examples:
297
```java
298
// Testing try-with-resources exception suppression
299
class FailingResource implements AutoCloseable {
300
@Override
301
public void close() throws Exception {
302
throw new IOException("Close failed");
303
}
304
}
305
306
Exception mainException = catchException(() -> {
307
try (FailingResource resource = new FailingResource()) {
308
throw new RuntimeException("Main operation failed");
309
}
310
});
311
312
assertThat(mainException)
313
.isInstanceOf(RuntimeException.class)
314
.hasMessage("Main operation failed")
315
.hasSuppressedExceptions(new IOException("Close failed"));
316
317
// Testing deep exception chains
318
Exception level3 = new SQLException("DB connection lost");
319
Exception level2 = new DataAccessException("Query failed", level3);
320
Exception level1 = new ServiceException("Service error", level2);
321
322
assertThat(level1)
323
.hasCauseInstanceOf(DataAccessException.class)
324
.hasRootCauseInstanceOf(SQLException.class)
325
.hasRootCauseMessage("DB connection lost");
326
```
327
328
## Types
329
330
```java { .api }
331
// Core exception testing interface
332
interface ThrowingCallable {
333
void call() throws Throwable;
334
}
335
336
// Exception capture utilities
337
class ThrowableAssert extends AbstractObjectAssert<ThrowableAssert, Throwable> {
338
// All assertion methods for Throwable
339
}
340
341
class NotThrownAssert {
342
void doesNotThrowAnyException()
343
NotThrownAssert doesNotThrowAnyExceptionOfTypes(Class<? extends Throwable>... types)
344
}
345
346
class ThrowableTypeAssert<T extends Throwable> {
347
ThrowableAssert isThrownBy(ThrowingCallable callable)
348
ThrowableAssert isThrownBy(ThrowingCallable callable, String description)
349
}
350
351
// Pattern for regex matching
352
class Pattern {
353
static Pattern compile(String regex)
354
}
355
356
// Common exception types for shortcuts
357
class IllegalArgumentException extends RuntimeException {}
358
class IllegalStateException extends RuntimeException {}
359
class NullPointerException extends RuntimeException {}
360
class IOException extends Exception {}
361
class RuntimeException extends Exception {}
362
```