Spring Boot 2.x Servlet Path在测试中被忽略



在我的application-test.properties中,我有这个server.servlet.context-path=/api

当我运行应用程序并用poster测试它时,它完全可以正常工作。但一旦我运行测试,它就会吞噬路径的/api部分。

所以基本上它应该是

localhost:8080/api/testUrl

但控制器仅在此处可用

localhost:8080/testUrl

我的测试类头

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@AutoConfigureMockMvc
public class QaControllerIntegrationTest {
private static final String QA_URL = "/api";
@Autowired
private MockMvc mockMvc;
@MockBean
private QaService qaService;
@Autowired
private TestRestTemplate testRestTemplate;

未实现任何设置行为。

和测试(只是为了完整性——如果我删除QA_URL,它们就会起作用(

@Test
void getQuestions() {
final ResponseEntity<List<QuestionAnswerDTO>> listResponseEntity = testRestTemplate.exchange(
QA_URL + "/questions", HttpMethod.GET, null, new ParameterizedTypeReference<>() {
});
assertThat(listResponseEntity.getStatusCode()).isEqualByComparingTo(HttpStatus.OK);
assertThat(listResponseEntity.getBody().get(0).getQuestion()).isEqualTo(QUESTION);
}
@Test
void addNewQa() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post(QA_URL + "/question")
.content(JacksonUtils.toString(questionAnswerDTO, false))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isCreated());
}

我在这里想念什么?

谢谢你=(

因为MockMvc没有自动配置上下文路径,因此不知道它。如果你想包含它,你可以执行:

MockMvcRequestBuilders.post(QA_URL + "/question").contextPath(QA_URL)

注意前缀必须匹配,以便Spring计算出剩余的路径。通常,测试不应该关心它们所处的上下文,因此永远不会包括上下文路径。

最新更新