Skip to content

Spring Boot 2.x Servlet Path is ignored in test

in my I have this server.servlet.context-path=/api

It works totally fine when I run the application and test it with postman. But as soon as I run my tests it swallows the part /api of the path.

So basically how it should be


but the controller is only available here


My Testclass head

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class QaControllerIntegrationTest {

    private static final String QA_URL = "/api";

    private MockMvc mockMvc;

    private QaService qaService;

    private TestRestTemplate testRestTemplate;

no setup behavior implemented.

and tests (only for the sake of completeness – they would work if I remove the QA_URL)

    void getQuestions() {
        final ResponseEntity<List<QuestionAnswerDTO>> listResponseEntity =
                QA_URL + "/questions", HttpMethod.GET, null, new ParameterizedTypeReference<>() {


    void addNewQa() throws Exception {
        mockMvc.perform( + "/question")
                .content(JacksonUtils.toString(questionAnswerDTO, false))

What do I miss here please?

Thank you =)



Because MockMvc isn’t autoconfigured with context path and thus is unaware of it. If you want to include it, you can do: + "/question").contextPath(QA_URL)

Notice prefix must match in order for Spring to figure out the remaining path. Typically a test shouldn’t care about the context they are in therefore context path is never included.

4 People found this is helpful