본문 바로가기
  • 소소한 개발자 이야기
Software/알고보면 쓸모있는 코딩스킬

[JUnit] POST, PATCH mvc.perform Content with Json

by Siwan_Min 2022. 10. 13.
728x90

JUnit Test를 할 때, perform() 메서드를 활용하여 controller 호출 방식을 지정한다. 또 controller 호출 시, 

어떠한 값을 주입할 것인가를 설정 하는데 그것이 바로 content()메서드이다. 어떠한 값을 주입을 할 것인가는 contentType에서 설정할 수 있다. String, JSON, XML 등을 설정 할 수 있다. JSON으로 할 경우 contentType을 JSON 으로 설정하고 content안에 JSON format으로 작성하면 Controller에서 RequestBody를 받을 시 JSON 형태로 받을 수 있다. 

 

하지만 여기서 주의해야 할 것이 있다. 예전 버전에서는 contentType를 JSON으로 설정하고 content안에 JSON format을 그냥 String 으로 작성하면 알아서 Parsing이 되어 RequestBody 에 주입이 되었으나, 어느 순간부터 이것이 되지 않았다. 

 

이를 해결하기 위해 Map을 활용하여 Key, Value를 넣어주고 이것을 JSON 형태로 바꾸어서 사용해야 한다. 

 

코드를 보면 아래와 같다. 

 

 @Test
    public void update() throws Exception {
        Map<String, String> input = new HashMap<>();
        input.put("name", "JOKER Bar");
        input.put("address", "Busan");

        mvc.perform(patch("/restaurants/1004")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(input)))
                //.content("{\"name:\":\"JOKER Bar\",\"address\":\"Busan\"}"))
                .andExpect(status().isOk());

        verify(restaurantService).updateRestaurant(1004L, "JOKER Bar", "Busan");
    }
}
 @PatchMapping(value = "/restaurants/{id}", produces = "application/json; charset=UTF-8")
    public String update(@PathVariable("id") Long id,
                         @RequestBody Restaurant resource){

        String name = resource.getName();
        String address = resource.getAddress();

        restaurantService.updateRestaurant(id, name, address);

        //URI location = new URI("/restaurants/" + restaurant.getId());
        return "{}";
    }

 

728x90

댓글