MemberController

...
    @PostMapping("/members")
    public Member save(@RequestBody Member member) {
        return memberService.create(member);
    }
...

MemberControllerTest

@WebMvcTest(MemberController.class)
class MemberControllerTest {

    @Autowired
    MockMvc mockMvc;

    @MockBean
    MemberService memberService;

    @Test
    void create() throws Exception {
        Member member = getMockMembers().get(0);
        when(memberService.create(member)).thenReturn(member);
        String memberString = "{\"name\":\"grace\",\"email\":\"govlmo91@gmail.com\"}";

        mockMvc.perform(post("/v1/members")
                    .content(memberString))
                .andExpect(status().isOk());
    }
}

테스트결과

요청값

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /v1/members
       Parameters = {}
          Headers = [Content-Length:"45"]
             Body = <no character encoding set>
    Session Attrs = {}

응답값

MockHttpServletResponse:
           Status = 415
    Error message = null
          Headers = [Accept:"application/json, application/octet-stream, application/xml, application/*+json, text/plain, text/xml, application/x-www-form-urlencoded, application/*+xml, multipart/form-data, multipart/mixed, */*"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

해결

MockMvc로 테스트할 때 ContentType을 지정해주자.

.contentType(MediaType.APPLICATION_JSON))

        mockMvc.perform(post("/v1/members")
                    .content(memberString)
                    .contentType(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isOk());

+ Recent posts