【问题标题】:"Could not open ServletContext resource" in test context测试上下文中的“无法打开 ServletContext 资源”
【发布时间】:2017-02-07 19:15:47
【问题描述】:

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

测试类:

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

要加载的类:

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

例外:

原因:org.springframework.beans.factory.BeanDefinitionStoreException:失败 解析配置类 [de.db.sus.converter.fia.business.algorithm.config.FiaConverterConfig]; 嵌套异常是 java.io.FileNotFoundException: 无法打开 ServletContext 资源 [/config/myConfig.properties]

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

如果我用@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)启动应用程序,属性就会被加载。但是我不能为每个单元测试启动整个应用程序。

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

【问题讨论】:

    标签: java spring unit-testing


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢,这有帮助。简而言之:“类路径:”丢失
    【解决方案2】:

    我配置maven war插件如下

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.1.1</version>
        <configuration>
           <warName>${war-file-name}</warName>
            <warSourceDirectory>src/main/webapp</warSourceDirectory>
            <failOnMissingWebXml>false</failOnMissingWebXml>
    
            <webResources>
              <resource>
                <!-- this is relative to the pom.xml directory -->
                <directory>src/main/resources</directory>
              </resource>
            </webResources>
         </configuration>
    </plugin>
    

    将以下部分配置为与您的 pom.xml 相关

     <webResources>
              <resource>
                <!-- this is relative to the pom.xml directory -->
                <directory>src/main/resources</directory>
              </resource>
     </webResources>
    

    更多信息请参考Adding and Filtering External Web Resources

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-16
      • 2015-01-16
      • 2022-01-18
      • 2018-12-18
      • 1970-01-01
      • 1970-01-01
      • 2016-02-22
      相关资源
      最近更新 更多