Spring Boot集成测试无法访问application.properties文件

Dan*_*elM 6 java junit spring integration-testing spring-boot

我有一些带有注释的类@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"
Run Code Online (Sandbox Code Playgroud)

这是application.properties文件的样子:

spring.data.rest.base-path=/api
spring.profiles.active=dev
...
Run Code Online (Sandbox Code Playgroud)

我还有一个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 {
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

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

my-project
|_ src
   |_ java
   |  |_ com.example.x
   |     |_ controller
   |        |_ MyRestController.java
   |
   |_ test
   |  |_ com.example.x
   |     |_ controller
   |        |_ MyRestControllerTest.java
   |
   |_ resources
      |_ application.properties
      |_ application-dev.properties
Run Code Online (Sandbox Code Playgroud)

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

Kev*_*don 0

application.properties不得位于测试类路径上。您应该在 IntelliJ 中为您的项目定义一个“测试资源”位置并application.properties在其中创建一个文件。

顺便说一句,我发现拥有一个单独的测试属性文件很有用,因为测试属性通常与正常的运行时环境不同。