Spring Boot Test MalformedURLException:未知协议:classpath

Evg*_*rov 8 java junit spring spring-test spring-boot

如果java.net.URL在Spring Boot应用程序中使用,使用classpath协议,它会按预期工作,因为Spring Boot注册URLStreamHandlerFactory.例如new URL("classpath: someFile.whatever").

但是当执行此代码时,java.net.MalformedURLException: unknown protocol: classpath将抛出JUnit测试异常.

URLStreamHandlerFactory在为JUnit测试初始化​​Spring上下文时,似乎没有注册适当的.

重现步骤:

1)创建Spring Boot Starter项目(例如,仅使用入门Web).

2)添加test.json文件src/main/resources

3)添加以下bean:

@Component
public class MyComponent {
    public MyComponent() throws MalformedURLException {
        URL testJson = new URL("classpath: test.json");
        System.out.println(testJson);
    }
}
Run Code Online (Sandbox Code Playgroud)

4)启动应用程序作为Java应用程序工作正常

5)运行默认的"contextLoads"测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringUrlTestApplicationTests {

    @Test
    public void contextLoads() {
    }

}
Run Code Online (Sandbox Code Playgroud)

java.net.MalformedURLException: unknown protocol: classpath抛出异常.

在JUnit测试中使用URL与classpath资源的合适方法是什么?

在真实的用例中,我无法改变new URL("classpath: test.json")它,因为它来自第三方库.

试图复制test.jsonsrc/test/resources,以测试是否错误可能由缺少的资源造成的-没有成功.

bor*_*ino 10

最简单和最简单的方法是在测试执行之前创建简单方法,即为"类路径"协议创建和注册处理程序.

    @BeforeClass
    public static void init() {
        org.apache.catalina.webresources.TomcatURLStreamHandlerFactory.getInstance();
    }
Run Code Online (Sandbox Code Playgroud)

我刚检查过,它工作正常.这种方法也使用了spring-boot应用程序内部