エキサイト株式会社の中です。
Java Spring BootでControllerのJSONの送信と受信のテストをする方法を説明します。
ユースケース
- Controllerのテストをする。 2.受け口をPostにする。 3.Jsonパラメータを送信する 4.Jsonパラメータを受信する
題材
コード例
コントローラーです。
@PostMapping("test") public String test(@RequestBody JsonBody jsonBody) { return jsonBody.getNaka(); } @Data public static class JsonBody{ private String naka; private String huga; }
入力例
Testクラスです。
@Test public void testJsonParameters() { try { MockHttpServletRequestBuilder getRequest = MockMvcRequestBuilders.post("/test"); final String contentAsString = this.mockMvc.perform(getRequest.with(request -> { final ObjectMapper objectMapper = new ObjectMapper(); final Map<String, String> requestParameters = Map.of( "naka","sho", "huga","fuga" ); try { request.setContent(objectMapper.writeValueAsString(requestParameters).getBytes(StandardCharsets.UTF_8)); request.setContentType(MediaType.APPLICATION_JSON_VALUE); return request; } catch (JsonProcessingException e) { e.printStackTrace(); throw new RuntimeException(); } })) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); assertEquals("sho", contentAsString); } catch (Exception e) { e.printStackTrace(); } }
出力例
テスト結果のコンソールです。
MockHttpServletRequest:
HTTP Method = POST
Request URI = /test
Parameters = {}
Headers = [Content-Type:"application/json"]
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type = com.controller.TestController
Method = com.controller.TestController#test(JsonBody)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"text/plain;charset=ISO-8859-1", Content-Length:"3"]
Content type = text/plain;charset=ISO-8859-1
Body = sho
Forwarded URL = null
Redirected URL = null
Cookies = []
Disconnected from the target VM, address: 'localhost:56988', transport: 'socket'
BUILD SUCCESSFUL in 50s
13 actionable tasks: 1 executed, 12 up-to-date
解説
final ObjectMapper objectMapper = new ObjectMapper();
final Map<String, String> requestParameters = Map.of(
"naka","sho",
"huga","fuga"
);
try {
request.setContent(objectMapper.writeValueAsString(requestParameters).getBytes(StandardCharsets.UTF_8));
request.setContentType(MediaType.APPLICATION_JSON_VALUE);
return request;
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException();
}
Mapでjsonパラメータを作成し、コンテンツにbyteで設定します。 コンテンツタイプは明示的にapplication/jsonに設定します。
出力結果が正しく取れているので jsonでもテストができることがわかりました。