Spring RESTコントローラでリソースを作成した後、次のようにヘッダ内の位置を返します。ユニットテストSpring RESTコントローラの 'Location'ヘッダ
@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>
Iを見込んでLocationヘッダのコンテキストプレフィックスhttp://localhost
を提供しなければならないように思えます。
解決策は、リダイレクト動作をテストします。 OPは、場所ヘッダーをテストしたかった。 今日まで、私は 'redirectedUrlPattern'について知りませんでした –