java - Spring REST API 服务单元测试(更新(PUT 方法))

标签 java spring api unit-testing http

我正在尝试在 API 中对 Controller 的服务进行单元测试,但出现以下错误:

2020-05-20 15:23:51.493  WARN 25469 --- [           main] .w.s.m.s.DefaultHandlerExceptionResolver : 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

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

您需要做的就是将正文内容添加到单元测试中,如下所示

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\"}")

关于java - Spring REST API 服务单元测试(更新(PUT 方法)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61922613/

相关文章:

java - Android - 使用 Picasso 从 JSON 获取图像

java - 为什么这个 SCJP 程序给出输出 21 但我得到 20?

java - Spring MVC 应用程序中用户之间的消息传递

java - 创建名称为 ‘client’ 的 bean 时出错

api - 如何使用.NET的Google自定义搜索API进行搜索?

java - 在 Java 中创建 API/库的步骤

c# - 如何在 Windows 窗体 C# 中同时将两个文件发布到 API

java - 有两个不确定参数的方法?

java - Spring RestTemplate 配置策略从单个 API 调用多个 rest 服务

java - 无需声明额外的 TaskScheduler