我从单元测试中得到一个我不太理解的结果。
控制器代码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是空的。我已经尝试了很多我在其他帖子和博客上读到的东西,无论我尝试什么,身体总是空的。在控制器响应中添加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表示的user,例如
状态码:201已创建响应主体
{
"userId": 1,
"firstName": "rick",
"lastName": "k",
"emailAddress": "rick@email.com",
"userName": "rk",
"password": "abc123"
}
使用SpringBoot 1.4.0.RELEASE,欢迎提供任何帮助或建议。
更新:由于某些原因,下面的模拟方法调用在测试控制器中返回null。
given(this.userService.saveUser(user)).willReturn(user);
这个帖子最终让我想到了一个解决方案:
当/then不返回预期值
改变这一行:
given(this.userService.saveUser(user)).willReturn(user);
given(this.userService.saveUser(any(User.class))).willReturn(user);