在application.properties中,我配置了server.contextPath=/app-service
。
不幸的是,这个值在测试环境中不存在:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { Application.class, SwaggerConfig.class })
@WebAppConfiguration
public class Swagger2MarkupTest {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void setUp() {
this.context.getServletContext().getContextPath(); // null
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
}
我需要使用默认情况下使用的Swagger Docket的contextPath
springfox.documentation.spring.web.paths.RelativePathProvider
通过
@Override
protected String applicationPath() {
return isNullOrEmpty(servletContext.getContextPath()) ? ROOT : servletContext.getContextPath();
}
所有关于RelativePathProvider的内容都比单元测试早得多。它不是将contextPath注入单元测试本身,因为它已经很晚,因为RelativePathProvider已经为SwaggerConfiguration调用了servletContext.getContextPath()
。
答案 0 :(得分:0)
你可以通过多种方式实现这一目标,其中有两个:
注入弹簧Environment
并获取属性值:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { Application.class, SwaggerConfig.class })
@WebAppConfiguration
public class Swagger2MarkupTest {
@Autowired
private WebApplicationContext context;
@Autowired
private Environment environment;
private MockMvc mockMvc;
@Before
public void setUp() {
environment.getProperty("server.contextPath"); // should return /app-service
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
}
使用@Value
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { Application.class, SwaggerConfig.class })
@WebAppConfiguration
public class Swagger2MarkupTest {
@Autowired
private WebApplicationContext context;
@Value("server.contextPath")
private String contextPath; // should populate with /app-service
private MockMvc mockMvc;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
}