Spring Boot 2.x测试中忽略了Servlet路径

huangapple go评论142阅读模式
英文:

Spring Boot 2.x Servlet Path is ignored in test

问题

在我的应用程序的application-test.properties文件中,我有以下配置:server.servlet.context-path=/api

当我运行应用程序并使用Postman进行测试时,它能够正常运行。但是一旦我运行测试,它就会忽略路径中的/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());
}

请问我在这里漏掉了什么?

谢谢 =)

英文:

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 = &quot;/api&quot;;

    @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&lt;List&lt;QuestionAnswerDTO&gt;&gt; listResponseEntity = testRestTemplate.exchange(
                QA_URL + &quot;/questions&quot;, HttpMethod.GET, null, new ParameterizedTypeReference&lt;&gt;() {
                });

        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 + &quot;/question&quot;)
                .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 =)

答案1

得分: 2

因为MockMvc未配置上下文路径,因此不知道它。如果您想要包含它,您可以这样做:

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

请注意,前缀必须匹配,以便Spring可以找出剩余的路径。通常测试不应关心它们所在的上下文,因此不会包含上下文路径。

英文:

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 + &quot;/question&quot;).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.

huangapple
  • 本文由 发表于 2020年8月23日 02:49:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63539931.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定