【发布时间】:2017-03-30 18:21:28
【问题描述】:
我有一些用@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
我在整个网络上找到了几个解决该问题的方法,但似乎没有一个对我有用。
【问题讨论】:
-
我没有看到你在哪里使用了这个属性
-
对不起,你是对的,我没有澄清这一点。它在 REST 控制器中用于定义所有端点的基本路径。那里的财产做得很好——正如我所提到的,我可以按预期从浏览器访问它们。唯一无法读取的地方是测试。
-
Intellij 似乎没有将 /resources 识别为资源文件夹。试试@PropertySource('file:/path/to/application.properties')
标签: java spring junit spring-boot integration-testing