我使用 Spring Boot 2.1.2.RELEASE 编写集成测试,无法设置所需的上下文路径。它始终等于空字符串(通过 servletContext.getContextPath() 获得)。
应用程序测试.属性:
server.servlet.context-path=/app
测试配置:
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@Import({MailSenderAutoConfiguration.class, ThymeleafAutoConfiguration.class})
@WebAppConfiguration
@TestPropertySource(locations="classpath:application-test.properties")
public class MyServiceTests {...}
调用代码:
@Value("#{'${application.base-url}' + servletContext.contextPath}")
private String siteUrl;
application-test.properties 中的其他属性按预期注入(inject)。上下文路径通常在我运行服务器时设置。我尝试以 @SpringBootTest 形式启动此测试,在变量 @TestPropertySource(locations="classpath:application-test.properties",properties = "server.servlet.context-path=/app") 中提供了上下文路径,但是没有结果。如何为我的测试设置上下文路径?
最佳答案
我找到了这样的解决方法:
文件 application-test.properties:
application.base-url=http://test.ru
server.servlet.context-path=/app
application.root-url=${application.base-url}${server.servlet.context-path:}
调用代码:
@Value("${application.root-url}")
private String siteUrl;
关于java - 如何在 Spring Boot 测试中设置 servlet 上下文路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57564089/