Springで提供されているモッククラス [Spring Framework Advent Calendar 2012 11日目 #jsug ]
Spring Framework Advent Calendar 2012の11日目です。
4巡目!間に合うか!(今23:50w)
Spring Frameworkではテスト用のモッククラスが提供されています。
一例としてMockHttpServletResponseを使ったテストケースが以下のようなものです。
テスト対象のメソッドはコントローラーのもので、HttpServletResponseを引数に取っています。
HttpServletResponseのようなインスタンス化できないものについて、モックがあらかじめ用意されているのは非常に便利です。うまく使ってJunitを書きたいですね。
ソース全体はここでアップしています。ざっくりな内容なのはご容赦を。。。
https://bitbucket.org/twopack/jsonrest/commits/f7038c946113f538ffc4d5ee1cd729d5
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