SpringBoot WebMvcTest中的Null Body

时间:2016-09-07 19:20:01

标签: junit spring-boot mockito

我从我的单元测试中得到了一个我不太了解的结果。

控制器代码

package com.rk.capstone.controllers;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.rk.capstone.model.domain.User;
import com.rk.capstone.model.services.user.IUserService;

/**
 * REST Controller for /register endpoint
 */
@RestController
@RequestMapping("/register")
public class RegisterController {

    private final IUserService userService;

    public RegisterController(IUserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public ResponseEntity<User> registerNewUser(@RequestBody User user) {
        if (userService.findByUserName(user.getUserName()) == null) {
            user = userService.saveUser(user);
            return ResponseEntity.status(HttpStatus.CREATED).body(user);
        } else {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(null);
        }
    }
}

单元测试代码:

package com.rk.capstone.controllers;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rk.capstone.model.dao.UserDao;
import com.rk.capstone.model.domain.User;
import com.rk.capstone.model.services.user.IUserService;

import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * Class Provides Unit Testing for RegisterController
 */
@RunWith(SpringRunner.class)
@WebMvcTest(RegisterController.class)
public class RegisterControllerTest {

    @MockBean
    private IUserService userService;

    @Autowired
    private MockMvc mockMvc;

    private User user;
    private String userJson;

    @Before
    public void setup() {
        user = new User("rick", "k", "rick@email.com", "rkow", "abc123");
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            userJson = objectMapper.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testRegisterNewUserPostResponse() throws Exception {
        given(this.userService.findByUserName(user.getUserName())).willReturn(null);
        given(this.userService.saveUser(user)).willReturn(user);
        Assert.assertNotNull("Mocked UserService is Null", this.userService);

        this.mockMvc.perform(post("/register/user").content(userJson).
                contentType(MediaType.APPLICATION_JSON)).
                andExpect(status().isCreated()).
                andDo(print()).andReturn();
    }

}

print()的结果如下,我不明白为什么Body是空的。我尝试了很多我在其他帖子和博客上阅读的内容,无论我尝试什么,Body总是空着的。在控制器响应中添加Content-Type标头没有任何区别。

MockHttpServletResponse:
           Status = 201
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

令我感到困惑的是,当我运行实际应用程序并使用PostMan对/ register / user端点执行POST时,响应包含我期望的正文和状态代码,通过JSON表示的用户,例如

状态代码:201已创建 回应机构

{
  "userId": 1,
  "firstName": "rick",
  "lastName": "k",
  "emailAddress": "rick@email.com",
  "userName": "rk",
  "password": "abc123"
}

使用SpringBoot 1.4.0.RELEASE赞赏任何帮助或想法。

UPDATE:由于某种原因,以下模拟方法调用在被测控制器中返回null。

given(this.userService.saveUser(user)).willReturn(user);

1 个答案:

答案 0 :(得分:3)

这个主题最终让我找到了解决方案:

Mockito when/then not returning expected value

更改了这一行:

given(this.userService.saveUser(user)).willReturn(user);

given(this.userService.saveUser(any(User.class))).willReturn(user);