【问题标题】:Spring boot restful service Post request always returns null as response message in test code using JunitSpring Boot Restful 服务 Post 请求始终返回 null 作为使用 Junit 的测试代码中的响应消息
【发布时间】:2018-10-26 00:55:36
【问题描述】:

这是一个演示控制器。

@PostMapping("/rest/new")
    public ResponseEntity<MessageDto> newUser(@RequestBody UserDto userDto) {
        return ResponseEntity.ok(new MessageDto().setMessage(userService.createUser(userDto)));
    }

这是服务层。

 @Override
    public String createUser(UserDto userDto) {
//        Do Something
        return "Successful!!";
    }

这是测试控制器的测试代码

@Test
    public void testPostRestController() throws Exception {
        UserDto userDto = new UserDto();
        userDto.setName("AA");
        userDto.setEmail("a@a.a");
        userDto.setId((long) 1);

        when(userService.createUser(userDto)).thenReturn("Successful!!");
        mockMvc.perform(post("/rest/new")
                    .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
                    .content(new ObjectMapper().writeValueAsString(userDto)))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
                .andExpect(jsonPath("$.message", is(userService.createUser(userDto))))
                .andDo(MockMvcResultHandlers.print());
    }

问题是当我运行测试代码时,它应该检查响应状态和响应消息。响应状态匹配,但问题是响应消息总是返回为空。

错误:

java.lang.AssertionError: JSON path "$.message"
Expected: is "Successful!!"
     but: was null

我错过了什么吗?

【问题讨论】:

    标签: rest unit-testing spring-boot junit


    【解决方案1】:

    尝试使用

    when(userService.createUser(any(UserDto.class))).thenReturn("Successful!!");
    

    代替

    when(userService.createUser(userDto)).thenReturn("Successful!!");
    

    这应该可以修复 NPE

    【讨论】:

    • 但它需要一个在运行时出错的转换。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    相关资源
    最近更新 更多