在Spring REST控制器中創建資源後,我將返回它在標題中的位置,如下所示。Spring REST控制器的單元測試'位置'標題
@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>
好像我必須爲期望的位置標題提供上下文前綴http://localhost
。
- 硬編碼上下文安全嗎?如果是這樣,爲什麼?
- 如果不是,那麼正確地爲測試用例生成正確的方法是什麼?
您的解決方案測試重定向行爲。 OP想要測試位置標頭。 我必須承認,直到今天我都不知道「redirectedUrlPattern」 –