簡體   English   中英

單元測試 Spring REST API 服務(更新(PUT方法))

[英]Unit testing Spring REST API Service (Update (PUT Method))

我正在嘗試在我的 API 中對我的 controller 的服務進行單元測試,但出現以下錯誤:

 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

這是我的測試 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()))); } }

這是我的服務

 @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); } }

如果有人能幫我解決這個問題,我將不勝感激。

據我了解,請求正文有問題,但我不知道該怎么做才能修復它。

如錯誤消息中所述,缺少requestbody

已解決 [org.springframework.http.converter.HttpMessageNotReadableException:缺少所需的請求正文

您需要做的就是像這樣將正文內容添加到單元測試中

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())));

你也可以像這樣傳遞內容

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM