我是模拟测试的新手。 我想为用户测试我的DAO。这是我的代码。
private UserService service;
private UserDAO mockDAO;
@Before
public void setUp(){
service=new UserService();
mockDAO=createMock(UserDAO.class);
service.setUserDao(mockDAO);
}
@Test
public void testAddUser(){
mockDAO.addUser( (User) EasyMock.anyObject());
EasyMock.replay(mockDAO);
User u=new User();
u.setUserName("x");
u.setPass("y");
service.registration(u);
EasyMock.verify(mockDAO);
}
当我运行它时,我收到此错误:
更新了stacktrace:
java.lang.AssertionError:
Unexpected method call UserDAO.checkUser(si.soa.rentacar.model.User@3655dba1):
UserDao.addUser(<any>): expected: 1, actual: 0
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:85)
at org.easymock.internal.ClassProxyFactory$MockMethodInterceptor.intercept(ClassProxyFactory.java:94)
at si.soa.rentacar.dao.UserDAO$$EnhancerByCGLIB$$1a06d4a9.checkUser(<generated>)
at si.soa.rentacar.ws.impl.UserService.registration(UserService.java:117)
at si.soa.rentacar._testUser.testAddUser(_testUser.java:58)
....
答案 0 :(得分:3)
您的UserService#registration
方法调用UserDAO#checkUser
方法,因此您需要将其添加到期望列表中。我不知道它的参数,所以我只为你提供下面的addUser调用示例:
@Test
public void testAddUser(){
// prepare data
User u = new User();
u.setUserName("x");
u.setPass("y");
// expectation section
mockDAO.addUser(u);
EasyMock.expectLastCall();
EasyMock.expect(mockDAO.checkUser(u)).andReturn(true);
EasyMock.replay(mockDAO);
// scenario
service.registration(u);
// verification
EasyMock.verify(mockDAO);
}