EasyMock 常见异常

时间:2023-03-09 19:04:50
EasyMock 常见异常

1.

java.lang.IllegalStateException: calling verify is not allowed in record state

含义:不允许在记录状态(record state)调用verify方法。

发生场景:不小心在调用EasyMock.replay(mockObj)之前,调用了EasyMock.verify(mockObj);

2.

java.lang.AssertionError:
Unexpected method call IDao.search(com.unittest.easymock.iargumentmatchertest.TestEntity@578486a3):
IDao.search(com.unittest.easymock.iargumentmatchertest.TestEntity@6ebc05a6): expected: 1, actual: 0

含义:从异常来看,search方法的参数的期待值和实际值不是同一个对象。

发生场景:在比较方法的入参的时候,一般是使用方法的equals方法来比较对象,如果equals方法没有重写而只是比较是否是同一个对象引用的话,很容易出现这种问题。

例:

    public void testEntity() {
ServiceClass serviceClass = new ServiceClass();
IDao idao = EasyMock.createMock(IDao.class);
serviceClass.setIdao(idao); TestEntity testEntity = new TestEntity();
TestEntity testEntity2 = new TestEntity();
EasyMock.expect(idao.search(testEntity)).andReturn(2); EasyMock.replay(idao); serviceClass.search(testEntity2); EasyMock.verify(idao);
}

解决方法:

1.重写equals方法

2.使用EasyMock的Argument Matchers提供的或自定义的方法来比较方法入参。