From 262c30ddc14aad946cc50ee344cb133d02a98d76 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Sat, 5 Nov 2022 16:44:53 -0700 Subject: [PATCH] Improve error message when DirtiesUrlFactoriesExtension fails See gh-33019 --- .../servlet/DirtiesUrlFactoriesExtension.java | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/DirtiesUrlFactoriesExtension.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/DirtiesUrlFactoriesExtension.java index db2e102e28..c3830c5440 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/DirtiesUrlFactoriesExtension.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/DirtiesUrlFactoriesExtension.java @@ -16,6 +16,7 @@ package org.springframework.boot.testsupport.web.servlet; +import java.lang.reflect.InaccessibleObjectException; import java.net.URL; import org.junit.jupiter.api.extension.AfterEachCallback; @@ -45,12 +46,18 @@ class DirtiesUrlFactoriesExtension implements BeforeEachCallback, AfterEachCallb } private void reset() { - ClassLoader classLoader = getClass().getClassLoader(); - if (ClassUtils.isPresent(TOMCAT_URL_STREAM_HANDLER_FACTORY, classLoader)) { - Class factoryClass = ClassUtils.resolveClassName(TOMCAT_URL_STREAM_HANDLER_FACTORY, classLoader); - ReflectionTestUtils.setField(factoryClass, "instance", null); + try { + ClassLoader classLoader = getClass().getClassLoader(); + if (ClassUtils.isPresent(TOMCAT_URL_STREAM_HANDLER_FACTORY, classLoader)) { + Class factoryClass = ClassUtils.resolveClassName(TOMCAT_URL_STREAM_HANDLER_FACTORY, classLoader); + ReflectionTestUtils.setField(factoryClass, "instance", null); + } + ReflectionTestUtils.setField(URL.class, "factory", null); + } + catch (InaccessibleObjectException ex) { + throw new IllegalStateException( + "Unable to reset field. Please run with '--add-opens=java.base/java.net=ALL-UNNAMED'", ex); } - ReflectionTestUtils.setField(URL.class, "factory", null); } }