以下课程很难进行单元测试:
public class UserService
{
public void Update(User user)
{
UserDAO userDAO = new UserDAO();
userDAO.update(user);
}
}
在使用JUnit和Mockito的实用单元测试一书的第7.6.2章中,Tomek Kaczanowsk建议我们注入以下内容:
public class UserService
{
private UserDAO _userDAO;
public UserService(UserDAO userDao)
{
_userDAO = userDAO;
}
public void Update(User user)
{
_userDAO.update(user);
}
}
但是,如何在不创建UserDao的情况下使用UserService?
public class UserController
{
public UserController()
{
// How do we initialize UserService without understanding about UserDAO here
}
public ActionResult Update()
{
var user = new User();
_userService.Update(user);
}
}
答案 0 :(得分:1)
从UserService创建一个接口,并将其传递给UserController的构造函数
public class UserController
{
public UserController(IUserService service )
{
_service = service;
}
public ActionResult Update()
{
var user = new User();
_service.Update(user);
}
}
IUserService
服务将通过Factory或Dependency Injection框架传递给UserController
(例如 Ninject / SimpleInjector )
答案 1 :(得分:0)
单元测试并不难,你只需要模仿DAO:
@Test
public void updateUser(@Mocked UserDAO dao) {
User user = new User();
new UserService().update(user);
new Verifications() {{ dao.update(user); }};
}
这使用JMockit模拟库。