You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot:如何将application.properties中server.contextPath注入MockServletContext

解决方案

我来帮你搞定这个测试环境下拿不到contextPath的问题,这种情况在Spring Boot测试里挺常见的,给你几个实用的解决思路:

方法一:直接通过@Value注入配置值(最推荐)

别绕ServletContext了,直接把配置属性注入到测试类里,这是最稳妥的方式,完全避开上下文初始化时机的问题:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { Application.class, SwaggerConfig.class })
@WebAppConfiguration
public class Swagger2MarkupTest {
    @Autowired
    private WebApplicationContext context;
    private MockMvc mockMvc;
    
    // 注意Spring Boot版本:1.x用server.contextPath,2.x及以上用server.servlet.context-path
    @Value("${server.contextPath:/}")
    private String contextPath;

    @Before
    public void setUp() {
        // 直接用这个变量就行,不用再从ServletContext折腾
        System.out.println(contextPath); // 这里会输出你配置的/app-service
        
        this.mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
    }
}

方法二:调整测试上下文配置,从ServletContext正确获取

如果你一定要从ServletContext拿值,可以试试这些调整:

  • 确认配置键正确:Spring Boot 1.x用server.contextPath=/app-service,2.x及以上要改成server.servlet.context-path=/app-service,写错键的话配置根本不会生效;
  • 显式指定Web环境:在@SpringBootTest里明确声明web环境类型,确保上下文是Web类型的:
    @SpringBootTest(classes = { Application.class, SwaggerConfig.class }, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
    
  • 换个时机获取:等MockMvc初始化完成后,或者通过RequestContextHolder获取请求上下文里的路径:
    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            String contextPath = attributes.getRequest().getContextPath();
            System.out.println(contextPath);
        }
    }
    

方法三:检查测试环境的配置文件

确保测试类能加载到正确的配置:

  • 如果你的测试用的是src/test/resources/application.properties,里面必须要有对应的server.contextPath=/app-service配置(或者确保主配置文件能被测试上下文加载);
  • 别在测试配置里不小心覆盖了这个值,比如写成空字符串或者其他路径。

内容的提问来源于stack exchange,提问作者Mahatma_Fatal_Error

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:34:27