java - 测试上下文中的 "Could not open ServletContext resource"

标签 java spring unit-testing

我正在尝试使用 Spring 创建单元测试。

测试类:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MyConfig.class})
public class MyTest{
@Test
public void ...
}

要加载的类:

@ConfigurationProperties()
@PropertySource("config/myConfig.properties")
@Component
public class MyConfig {}

异常(exception):

Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [de.db.sus.converter.fia.business.algorithm.config.FiaConverterConfig]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/config/myConfig.properties]

我找到了用于 Web 应用程序和/或基于 xml 的配置的资源,但不适用于传输它们。

如果我使用 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 启动应用程序,属性将被加载。但我无法为每个单元测试启动整个应用程序。

我已验证该文件存在于目录 test/resources/config/中

最佳答案

似乎找不到请求的属性。我建议这样做:

如果请求的属性文件在您的类路径中,您可以通过编写下一行来修复上面的问题:

@PropertySource("classpath:config/myConfig.properties")

关于java - 测试上下文中的 "Could not open ServletContext resource",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39770694/

相关文章:

Java 使用文本文件中的条目创建一个组合框

spring.data.ldap 在 application.properties 中有多个 spring.ldap.urls

python - Python 中的自定义错误消息

java - 在SDN 5.0.0中创建neo4j sessionfactory

java - StoredProcedureItemReader 和 JdbcCursorItemReader 的游标数据保留在 java 堆内存中还是数据库中

javascript - Observable<void> 不调用订阅者

javascript - Istanbul 尔代码覆盖率检查我的规范文件而不是源代码的覆盖率?

java - Spring-data-neo4j-4 如何在@NodeEntity注解中指定多个标签

java - 阅读 nextLine 的更好方法

java - 在 Kotlin 中实例化对象时如何覆盖方法?