使用Mockito我的API进行测试,发现对我来说非常奇怪。创建id属性不为null的新用户,调用save(用户)模拟并获取user.id为null。 "真" save方法的工作方式不同,它保存实体并将其id属性设置为唯一的long值,而不是null。 代码服务层:
public static void main(String[] args){
int num = 0;
int eachNum = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter your number here: ");
num = input.nextInt();
int num2 = num;
int length = String.valueOf(num).length()-1;
while ( length >= 0 ) {
int substraction =(int) Math.pow(10, length);
int sub = (int) substraction;
eachNum = (num2 / sub) % 10;
System.out.print(eachNum + "\t");
length--;
}
}//end main
API控制器:
@Override
public Long save(User user) {
userDao.save(user);
return user.getId();
}
并测试:
@RequestMapping(value = "/user", method = RequestMethod.POST, produces = {"application/json"})
@ResponseStatus(HttpStatus.OK)
public @ResponseBody String addUser(@RequestBody String jsonString) {
User user = User.fromJson(jsonString);
userService.save(user);
return user.toJson();
}
从未通过的因为id = 1且actual的预期用户是id = null的用户。 请帮忙找到哪个东西可以将user.id设置为null? 再次,服务方法(和dao)保存工作完美。
增加: 道码:
@Test
public void addUser() throws Exception {
Role role = new Role(1L, "ROLE_USER");
User user = new User (1L, "Test user", "Test password", true, role);
when(roleService.findByName(role.getName())).thenReturn(role);
when(userService.save(user)).thenReturn(1L);
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/user").content(user.toJson())).andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andReturn();
assertEquals(user.toJson(), result.getResponse().getContentAsString());
verify(userService).save(user);
}