Debian Codegraph @

junit-jupiter-api/src/main/java/org/junit/jupiter/api/AssertThrows.java

raw symbols SCIP
1 /*
2 * Copyright 2015-2024 the original author or authors.
3 *
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v2.0 which
6 * accompanies this distribution and is available at
7 *
8 * https://www.eclipse.org/legal/epl-v20.html
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 * {@code AssertThrows} is a collection of utility methods that support asserting
24 * an exception of an expected type is thrown.
25 *
26 * @since 5.0
27 */
28 class AssertThrows {
29
30 private AssertThrows() {
31 /* no-op */
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 }