2

我是模拟测试的新手。我想为用户测试我的 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);

}

当我运行它时,我收到此错误:

更新了堆栈跟踪:

  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)
     ....
4

1 回答 1

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);

}
于 2013-05-15T20:12:11.667 回答