Debian Codegraph @

junit-jupiter-api/src/main/java/org/junit/jupiter/api/AssertInstanceOf.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 org.junit.jupiter.api.AssertionFailureBuilder.assertionFailure;
14
15 import java.util.function.Supplier;
16
17 /**
18 * {@code AssertInstanceOf} is a collection of utility methods that support
19 * asserting that an object is of an expected type — in other words, if it
20 * can be assigned to the expected type.
21 *
22 * @since 5.8
23 */
24 class AssertInstanceOf {
25
26 private AssertInstanceOf() {
27 /* no-op */
28 }
29
30 static <T> T assertInstanceOf(Class<T> expectedType, Object actualValue) {
31 return assertInstanceOf(expectedType, actualValue, (Object) null);
32 }
33
34 static <T> T assertInstanceOf(Class<T> expectedType, Object actualValue, String message) {
35 return assertInstanceOf(expectedType, actualValue, (Object) message);
36 }
37
38 static <T> T assertInstanceOf(Class<T> expectedType, Object actualValue, Supplier<String> messageSupplier) {
39 return assertInstanceOf(expectedType, actualValue, (Object) messageSupplier);
40 }
41
42 private static <T> T assertInstanceOf(Class<T> expectedType, Object actualValue, Object messageOrSupplier) {
43 if (!expectedType.isInstance(actualValue)) {
44 assertionFailure() //
45 .message(messageOrSupplier) //
46 .reason(actualValue == null ? "Unexpected null value" : "Unexpected type") //
47 .expected(expectedType) //
48 .actual(actualValue == null ? null : actualValue.getClass()) //
49 .buildAndThrow();
50 }
51 return expectedType.cast(actualValue);
52 }
53
54 }