简体   繁体   中英

Unit testing Spring REST API Service (Update (PUT Method))

I'm trying to unit test a service for my controller in my API but i'm getting the following error:

 2020-05-20 15:23:51.493 WARN 25469 --- [ main].wsmsDefaultHandlerExceptionResolver: Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity<com.tropicalia.meu_cardapio.domain.user.User> com.tropicalia.meu_cardapio.api.user.update.UserUpdateRest.update(com.tropicalia.meu_cardapio.domain.user.User,java.lang.Long)] MockHttpServletRequest: HTTP Method = PUT Request URI = /users/89 Parameters = {} Headers = [Content-Type:"application/json"] Body = <no character encoding set> Session Attrs = {} Handler: Type = com.tropicalia.meu_cardapio.api.user.update.UserUpdateRest Method = com.tropicalia.meu_cardapio.api.user.update.UserUpdateRest#update(User, Long) Async: Async started = false Async result = null Resolved Exception: Type = org.springframework.http.converter.HttpMessageNotReadableException ModelAndView: View name = null View = null Model = null FlashMap: Attributes = null MockHttpServletResponse: Status = 400 Error message = null Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"] Content type = null Body = Forwarded URL = null Redirected URL = null Cookies = [] java.lang.AssertionError: Status Expected:202 Actual:400

This is my test class:

 @RunWith(SpringRunner.class) @WebMvcTest(UserUpdateRest.class) public class UpdateUserTest { @Autowired private MockMvc mvc; @MockBean private UserUpdateService service; @Test public void updateUser_whenPutUser() throws Exception { User user = new User(); user.setName("Test Name"); user.setId(89L); given(service.updateUser(user.getId(), user)).willReturn(user); mvc.perform(put("/users/" + user.getId().toString()).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isAccepted()).andExpect(jsonPath("name", is(user.getName()))); } }

And this is my service

 @Service public class UserUpdateService { @Autowired UserRepository repository; public User updateUser(Long id, User user) { repository.findById(id).orElseThrow(() -> new EntityNotFoundException("User not found.")); return repository.save(user); } }

Would really appreciate if someone could help me with this one.

From what i understand, there's something wrong with the request body but i have no idea what to do to fix it.

As specified in the error message, requestbody is missing.

Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing

All you need to do is add body content to the unit test like this

ObjectMapper mapper = new ObjectMapper();

mvc.perform(put("/users/" + user.getId().toString())
      .contentType(MediaType.APPLICATION_JSON))
      .content(mapper.writeValueAsString(user))
      .andExpect(status().isAccepted())
      .andExpect(jsonPath("name", is(user.getName())));

you can also pass content like this

.content("{\"id\":\"89\", \"name\":\"Test Name\"}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM