Spring REST Controller的单元测试'Location'标题

Bil*_*rza 6 rest testng spring mockmvc

在Spring REST Controller中创建资源后,我将在标题中返回它的位置,如下所示.

@RequestMapping(..., method = RequestMethod.POST)
public ResponseEntity<Void> createResource(..., UriComponentsBuilder ucb) {

    ...

    URI locationUri = ucb.path("/the/resources/")
        .path(someId)
        .build()
        .toUri();

    return ResponseEntity.created(locationUri).build();
}
Run Code Online (Sandbox Code Playgroud)

在单元测试中,我正在检查其位置如下.

@Test
public void testCreateResource(...) {
    ...
    MockHttpServletRequestBuilder request = post("...")
        .content(...)
        .contentType(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON);

    request.session(sessionMocked);

    mvc.perform(request)
        .andExpect(status().isCreated())
        .andExpect(header().string("Location", "/the/resources" + id);
}
Run Code Online (Sandbox Code Playgroud)

此结果案例失败,并显示以下消息.

java.lang.AssertionError: Response header Location expected:</the/resources/123456> but was:<http://localhost/the/resources/123456>
Run Code Online (Sandbox Code Playgroud)

好像我必须为http://localhost期望的Location头提供上下文前缀.

  • 硬编码上下文是否安全?如果是这样,为什么?
  • 如果没有,为测试用例正确生成它的正确方法是什么?

Sur*_*jaj 5

我猜是因为您UriComponentsBuilder用来构建URI,所以它是在位置标头中设置主机名。如果您使用过Just之类的东西new URI("/the/resources"),您的测试将通过。

在您的情况下,我将使用redirectedUrlPattern来匹配重定向URL:

.andExpect(redirectedUrlPattern("http://*/the/resources"))

这将匹配任何主机名,因此您不必对localhost进行硬编码。AntPathMatcher在此处了解更多有关可以使用的不同模式的信息

  • 您的解决方案将测试重定向行为。OP希望测试位置标头。我必须承认,直到今天我都不知道`redirectedUrlPattern`。 (3认同)

小智 3

如果您不需要在响应的 Location 标头中包含完整的 URI(即没有要求、设计约束等...):请考虑切换到使用相对 URI(从 HTTP 标准的角度来看这是有效的 - 请参阅 [1 ]: https://www.rfc-editor.org/rfc/rfc7231)相对 URI 是现代浏览器和库支持的提议标准。这将允许您测试端点的行为并使其从长远来看不那么脆弱。

如果您需要断言完整路径,因为您使用的是 MockMvc,您可以将测试请求中的 uri 设置为您想要的:

@Autowired
private WebApplicationContext webApplicationContext;

@Test
public void testCreateResource() {
    MockMvc mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    mvc.perform(MockMvcRequestBuilders.get(new URI("http://testserver/the/resources")));
Run Code Online (Sandbox Code Playgroud)

这将使注入的构建器在调用构建时生成“http://testserver”。请注意,如果将来的框架更改删除了此测试行为,可能会给您带来麻烦。