java - 如何在 Spring Boot 测试中设置 servlet 上下文路径?

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

我使用 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/

相关文章:

java - 用于匹配单词、特殊字符和日期的正则表达式

java - org.postgresql.util.PSQLException : The server does not support SSL

spring-boot - 如何使用 swagger-ui(springfox-swagger2 和 springfox-swagger-ui)和 spring-boot 应用程序上传多个文件?

java - 如何生成jhipster View ?

java - 如何制作 primefaces 动态工具栏

java - 可以从 WEB-INF\lib\{*.jar}\META-INF\resources\WEB-INF 目录访问 tld 文件吗?

java - Spring JDBCTemplate 除了 apache commons 之外还有其他 MySQL 数据源吗?

java - 根据给定的纬度、经度和半径值在 Java 中查找最小和最大纬度和经度

spring-boot - 如何确定向远程 Spring Boot 服务器发送请求的 URL?

java - 实例化新的数组双端队列以保持通用