4巡目!間に合うか!(今23:50w)
Spring Frameworkではテスト用のモッククラスが提供されています。
一例としてMockHttpServletResponseを使ったテストケースが以下のようなものです。
@Test
public void testGetName_Tom() throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(sut.getName(response, 1), is("Tom"));
assertThat(response.getStatus(), is(HttpServletResponse.SC_OK));
}
テスト対象のメソッドはコントローラーのもので、HttpServletResponseを引数に取っています。
@RequestMapping(value = "/person/name/{id}", method = RequestMethod.GET)
public @ResponseBody String getName(HttpServletResponse response,
@PathVariable int id) {
if(id == 1) {
return "Tom";
}
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return "Not found.";
}
HttpServletResponseのようなインスタンス化できないものについて、モックがあらかじめ用意されているのは非常に便利です。うまく使ってJunitを書きたいですね。
ソース全体はここでアップしています。ざっくりな内容なのはご容赦を。。。
https://bitbucket.org/twopack/jsonrest/commits/f7038c946113f538ffc4d5ee1cd729d5
具体的に使えるモックは以下を参照。
返信削除http://static.springsource.org/spring/docs/1.2.9/api/org/springframework/mock/web/package-summary.html