| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
package org.junit.jupiter.api; |
| 12 |
|
| 13 |
import static java.lang.String.format; |
| 14 |
import static org.junit.jupiter.api.AssertionFailureBuilder.assertionFailure; |
| 15 |
import static org.junit.jupiter.api.AssertionUtils.getCanonicalName; |
| 16 |
|
| 17 |
import java.util.function.Supplier; |
| 18 |
|
| 19 |
import org.junit.jupiter.api.function.Executable; |
| 20 |
import org.junit.platform.commons.util.UnrecoverableExceptions; |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
class AssertThrows { |
| 29 |
|
| 30 |
private AssertThrows() { |
| 31 |
|
| 32 |
} |
| 33 |
|
| 34 |
static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executable) { |
| 35 |
return assertThrows(expectedType, executable, (Object) null); |
| 36 |
} |
| 37 |
|
| 38 |
static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executable, String message) { |
| 39 |
return assertThrows(expectedType, executable, (Object) message); |
| 40 |
} |
| 41 |
|
| 42 |
static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executable, |
| 43 |
Supplier<String> messageSupplier) { |
| 44 |
|
| 45 |
return assertThrows(expectedType, executable, (Object) messageSupplier); |
| 46 |
} |
| 47 |
|
| 48 |
@SuppressWarnings("unchecked") |
| 49 |
private static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executable, |
| 50 |
Object messageOrSupplier) { |
| 51 |
|
| 52 |
try { |
| 53 |
executable.execute(); |
| 54 |
} |
| 55 |
catch (Throwable actualException) { |
| 56 |
if (expectedType.isInstance(actualException)) { |
| 57 |
return (T) actualException; |
| 58 |
} |
| 59 |
else { |
| 60 |
UnrecoverableExceptions.rethrowIfUnrecoverable(actualException); |
| 61 |
throw assertionFailure() |
| 62 |
.message(messageOrSupplier) |
| 63 |
.expected(expectedType) |
| 64 |
.actual(actualException.getClass()) |
| 65 |
.reason("Unexpected exception type thrown") |
| 66 |
.cause(actualException) |
| 67 |
.build(); |
| 68 |
} |
| 69 |
} |
| 70 |
throw assertionFailure() |
| 71 |
.message(messageOrSupplier) |
| 72 |
.reason(format("Expected %s to be thrown, but nothing was thrown.", getCanonicalName(expectedType))) |
| 73 |
.build(); |
| 74 |
} |
| 75 |
|
| 76 |
} |