java – Spring Boot集成测试无法到达application.properties文件

前端之家收集整理的这篇文章主要介绍了java – Spring Boot集成测试无法到达application.properties文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一些使用@RestController注释的类,我正在尝试使用MockMvc类进行测试.端点从Web应用程序正确响应,但在运行测试时出现以下错误(来自IntelliJ IDEA):

java.lang.IllegalArgumentException: Could not resolve placeholder
'spring.data.rest.base-path' in string value "${spring.data.rest.base-path}/whatever"

这就是application.properties文件的样子:

spring.data.rest.base-path=/api
spring.profiles.active=dev
...

我还有一个名为application-dev.properties的文件,其中包含其他(不同的)属性.

这是测试类的注释方式:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest // Also tried: @WebAppConfiguration
@ActiveProfiles("dev")
// Also tried: @PropertySource("classpath:application.properties")
// Also tried: @TestPropertySource("classpath:application.properties")
public class MyRestControllerTest {
    ...
}

另一方面,这是REST控制器的实现方式(使用有问题的属性):

@RestController
@RequestMapping("${spring.data.rest.base-path}/whatever")
public class MyRestController {
    ...
}

这就是应用程序主类的外观:

@SpringBootApplication(scanBasePackages = {...})
@EnableJpaRepositories({...})
@EntityScan({...})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

最后,这是项目结构的(子集):

my-project
|_ src
   |_ java
   |  |_ com.example.x
   |     |_ controller
   |        |_ MyRestController.java
   |
   |_ test
   |  |_ com.example.x
   |     |_ controller
   |        |_ MyRestControllerTest.java
   |
   |_ resources
      |_ application.properties
      |_ application-dev.properties

我在整个网络上找到了几个问题的解决方案,但它们似乎都不适合我.

最佳答案
答案最终与Spring注释和IntelliJ配置无关,而是与MockMvc有关,特别是与测试’setUp上使用的类和方法MockMvcBuilders.standaloneSetup有关.这不会使用应用程序的上下文,因此无法正确读取依赖于它的属性.

将其更改为MockMvcBuilders.webAppContextSetup后,(来自文档)

Build[s] a MockMvc instance using the given,fully initialized (i.e.,
refreshed) WebApplicationContext.

一切正常.对于集成测试,使用它更有意义,不是吗?

感谢您的所有时间和精力.很抱歉没有显示提到的setUp方法,但我没想到问题可能是由那里引起的.

原文链接:https://www.f2er.com/spring/432387.html

猜你在找的Spring相关文章