在 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();
}
在单元测试中,我正在检查其位置如下。
@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);
}
此结果案例失败并显示以下消息。
java.lang.AssertionError: Response header Location expected:</the/resources/123456> but was:<http://localhost/the/resources/123456>
似乎我必须在预期中为 Location header 提供上下文前缀
http://localhost
。最佳答案
我猜是因为你正在使用 UriComponentsBuilder
要构建您的 URI,它会在您的位置 header 中设置主机名。你是否使用过类似 new URI("/the/resources")
的东西,您的测试将通过。
在你的情况下,我会使用 redirectedUrlPattern匹配重定向 URL:.andExpect(redirectedUrlPattern("http://*/the/resources"))
这将匹配任何主机名,因此您不必对 localhost 进行硬编码。详细了解可以与 AntPathMatcher
一起使用的不同模式here .
关于spring - Spring REST Controller 的单元测试 'Location' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40931556/