【发布时间】:2019-03-26 22:11:23
【问题描述】:
如果在 Spring Boot 应用程序中使用 java.net.URL,使用 classpath 协议,它会按预期工作,因为 Spring Boot 注册了 URLStreamHandlerFactory。例如new URL("classpath: someFile.whatever").
但是当这个代码作为 JUnit 测试执行时,java.net.MalformedURLException: unknown protocol: classpathexception 被抛出。
在为 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 方库。
尝试将test.json 复制到src/test/resources 中,以测试错误是否可能是由于缺少资源导致的 - 没有成功。
【问题讨论】:
-
如果不能更改第三方库define the URLhandler,否则容易使用@Resource - examples
标签: java spring spring-boot junit spring-test