Skip to content
Advertisement

Spring Boot 2.x Servlet Path is ignored in test

in my application-test.properties 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

localhost:8080/api/testUrl

but the controller is only available here

localhost:8080/testUrl

My Testclass head

@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;

no setup behavior implemented.

and tests (only for the sake of completeness – they would work if I remove the 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());
    }

What do I miss here please?

Thank you =)

Advertisement

Answer

Because MockMvc isn’t autoconfigured with context path and thus is unaware of it. If you want to include it, you can do:

MockMvcRequestBuilders.post(QA_URL + "/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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement