我是Junit的新手。请帮我测试Spring的hibernate Controller,ContentType是application / json
以下是我的控制器
@Controller
@RequestMapping(value="/users")
public class UserServiceImpl implements UserService{
private static Logger logger = Logger.getLogger(UserService.class);
private UserDao userDao;
@Autowired
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@RequestMapping(method = RequestMethod.POST,headers = "content-type=application/json")
@ResponseBody
public long addUser(@RequestBody UserForm user) {
logger.info("Creating new user {}"+ user);
return userDao.create(user);
}
@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
@ResponseBody
public User findUser(@PathVariable(value = "userId") String userId) {
logger.info("Reading user with id {}"+ userId);
User user = userDao.find(userId);
Validate.isTrue(user != null, "Unable to find user with id: " + userId);
return user;
}
@RequestMapping(value = "/{userId}", method = RequestMethod.PUT,headers = "content-type=application/json")
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void updateUser(@PathVariable(value = "userId") String userId, @RequestBody UserForm user) {
logger.info("Updating user with id {} with {}"+ userId +"->"+ user);
Validate.isTrue(userId.equals(user.getUserId()), "userId doesn't match URL userId: " + user.getUserId());
userDao.update(user);
}
@RequestMapping(value = "/{userId}", method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void deleteUser(@PathVariable(value = "userId") String userId) {
logger.info("Deleting user with id {}"+ userId);
userDao.delete(userId);
}
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public List<User> list() {
logger.info("Listing users");
return new ArrayList<User>(userDao.getUsers());
}
}
任何人都可以向我发送任何一个CRUD操作的Junit测试用例。
先谢谢
SRIKANTH
答案 0 :(得分:1)
如果你只是想测试你的控制器,那么我会说嘲笑DAO。你不必关心内容类型,因为Spring会照顾它们。您感兴趣的是控制器方法返回的内容。如果你想测试用户实际保存到数据库的DAO,那就是另一个故事。
但仅仅是为了测试那个控制器能做到它应该做的事情,比如这样的东西。示例使用EasyMock。我没有编译这个例子,所以它可能有拼写错误。
import static org.easymock.EasyMock.createNiceMock;
public class ControllerTest {
private UserServiceImpl userService;
private UserDao userDaoMock;
@Before
public void setup() {
userDaoMock = createNiceMock(UserDao.class);
userService = new UserServiceImpl();
userSerivce.setUserDao(userDaoMock);
}
@Test
public void testAddUser() {
UserForm userForm = new UserForm();
long expectedResult = 5L;
expect(userDaoMock.create(userForm)).andReturn(expectedResult);
replay(userDaoMock);
long actualResult = userService.addUser(userForm);
verify(userDaoMock);
assertEquals(expectedResult, actualResult);
}
}