java - 执行 JUnit 测试时 ServletContext 无法打开属性文件

标签 java spring spring-boot spring-boot-test

我正在使用 JUnit 4 和 MockMvc 测试 REST Controller 。当我几周前编写测试时,一切都按预期进行。我对代码做了一些修改,但没有更改 JUnit 测试。现在,当我尝试运行我的测试时,出现错误:

Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/application.properties]

这是我的代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyServerApplication.class)
@SpringBootTest
@Transactional
public class MovieControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private MovieRepository movieRepository;

    @Autowired
    private WebApplicationContext wac;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    // Some tests
}

我的主课:

@SpringBootApplication
public class MyServerApplication{

    public static void main(String[] args) {
        SpringApplication.run(MyServerApplication.class, args);
    }
}

我的application.properties 文件位于src/main/resources。我没有移动这个文件,除了在我的服务中添加一些代码并在我的文件中添加一些属性外,我什么也没做。

我阅读了 SO 问题和文档,并尝试了这些解决方案:

  • 检查 src/main/resources 是否仍在我的测试类路径中
  • 在我的测试注释下添加@PropertySource("classpath:application.properties");它没有用,所以我尝试创建一个 src/test/resources,里面有 application.properties 的副本,如一篇文章中所建议的
  • 在主类而不是测试类中添加@PropertySource("classpath:application.properties")
  • 添加@WebAppConfiguration注解
  • 添加@WebMvcTest注解

我当然没有同时尝试所有这些解决方案,我在每次失败后删除了添加的代码。

我仍然可以毫无问题地运行我的代码,只有测试类导致 FileNotFoundException

如何解决?为什么我的测试类有问题,但在我运行服务器时一切正常?

最佳答案

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyServerApplication.class)
@SpringBootTest
@Transactional
public class MovieControllerTest { ... }

这是你在测试课上的内容。使用 @SpringBootTest 时,不应使用 @ContextConfiguration(请参阅 Spring Boot 引用指南的 testing chapter)。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@Transactional
public class MovieControllerTest { ... }

我还建议您使用 Spring Boot 进行测试,而不是尝试手动执行操作。对于模拟 mvc 测试 Spring Boot 应用程序,已经为您完成了特殊的切片和设置。

要启用此功能,请将 @AutoConfigureMockMvc 添加到您的测试中,并将 @Autowired 放在 MockMvc 字段中(并删除您的 @Before 方法)。

关于java - 执行 JUnit 测试时 ServletContext 无法打开属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43934742/

相关文章:

Java 流发生情况

java - spring-data-jpa 存储库在查询中使用 Collection 作为 @Param

java - elasticsearchrepository 在字段中保存空值

java - Android:使用带有端口号的 Uri.Builder().build() 创建 URL

java - Spark SQL (Java) - 连接 X 个文件的廉价方法?

java - Spring boot - 在测试中注入(inject)的存储库映射为空

spring ioc注入(inject)接口(interface)的具体实现来测试

java - 在 gradle 多项目 [spring 数据] 中将主题存储库注入(inject) DataService 失败

java - 如何修复 Spring Boot 不支持的请求方法 'POST'?

java - 使用 Java Bean 类的 application.properties 文件中的 Spring Boot : Reading spring. jms.jndi-name 属性