【问题标题】:How to send request to controller using mockmvs on junit with object parameter?如何在junit中使用带有对象参数的mockmvc向控制器发送请求?
【发布时间】:2020-07-28 14:13:16
【问题描述】:

我正在尝试向控制器方法发送请求并对其进行测试,但我需要发送一个 dto 类作为参数。代码如下:

 @BeforeEach
    void setUp() {
        saveUser();
    }

    @Test
    void saveUser() {
        UserDto userDto = new UserDto();
        userDto.setUsername("John");
        userDto.setEmail("john@foo.com");
        userDto.setPassword("password");

        this.mockMvc.perform(post("localhost:8080/registerUser")
                .contentType(MediaType.APPLICATION_JSON)
                .body(userDto)
                .andExpect....
    }

这里我需要发送 userDto 作为参数,但我不能,我如何发送它并在 andExpect 块中期待结果?

【问题讨论】:

    标签: unit-testing junit mocking mockito mockmvc


    【解决方案1】:

    将您的实体映射到 json 并将 body 更改为 content,如下所示:

    final ObjectMapper mapper = new ObjectMapper();
    
    this.mockMvc.perform(post("localhost:8080/registerUser")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(mapper.writeValueAsString(userDto))
                    .accept(MediaType.APPLICATION_JSON))
                    .andExpect(status().isOk());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-07
      • 2020-11-16
      • 1970-01-01
      • 2022-12-22
      • 2018-06-29
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      相关资源
      最近更新 更多