如果在 Spring Boot 应用程序中使用 java.net.URL
,使用 classpath
协议(protocol),它会按预期工作,因为 Spring Boot 注册了 URLStreamHandlerFactory
。例如新 URL("classpath: someFile.whatever")
。
但当此代码作为 JUnit 测试执行时,java.net.MalformedURLException: unknown protocol: classpath
异常被抛出。
当为 JUnit 测试初始化 Spring 上下文时,似乎没有注册适当的 URLStreamHandlerFactory
。
重现步骤:
1) 创建 Spring Boot Starter 项目(例如仅使用 starter Web)。
2) 在src/main/resources
中添加test.json
文件
3)添加以下bean:
@Component
public class MyComponent {
public MyComponent() throws MalformedURLException {
URL testJson = new URL("classpath: test.json");
System.out.println(testJson);
}
}
4) 以 java 应用程序启动应用程序正常
5) 运行默认的“contextLoads”测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringUrlTestApplicationTests {
@Test
public void contextLoads() {
}
}
java.net.MalformedURLException: unknown protocol: classpath
异常被抛出。
在 JUnit 测试中将 URL 与类路径资源一起使用的合适方法是什么?
在实际用例中,我无法更改 new URL("classpath: test.json")
,因为它来自第 3 方库。
尝试复制 src/test/resources
中的 test.json
,以测试错误是否由缺少资源引起 - 没有成功。
最佳答案
最短和最简单的方法是在测试执行之前创建简单的方法,即为“类路径”协议(protocol)创建和注册处理程序。
@BeforeClass
public static void init() {
org.apache.catalina.webresources.TomcatURLStreamHandlerFactory.getInstance();
}
我刚刚检查过,它工作正常。这种方法也在 spring-boot 应用程序内部使用
关于java - Spring Boot 测试 MalformedURLException : unknown protocol: classpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52936054/