我正在尝试使用 JUnit4 和 EasyMock 2.4 测试使用休眠标准 API 的 dao 方法。
当我运行测试夹具“testGetAsset”时,我收到以下异常:
java.lang.AssertionError:
Unexpected method call add(name=Test):
add(name=Test): expected: 1, actual: 0
add(source=GSFP): expected: 1, actual: 0
uniqueResult(): expected: 1, actual: 0
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:32)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:61)
at $Proxy7.add(Unknown Source)
at com.hsbc.sfd.funddb.persistence.dao.AssetDaoImpl.getAsset(AssetDaoImpl.java:80)
at com.hsbc.sfd.funddb.persistence.AssetDaoTest.testGetAsset(AssetDaoTest.java:62)
我认为这个问题与未使用 Asset.class 初始化的模拟标准对象有关,但我是 EasyMock 和模拟对象的初学者,所以如果有人可以看看并告诉我,我将不胜感激我需要做什么才能使测试通过。
非常感谢,马克
代码如下:
道法
public Asset getAsset(String name, Source source) {
return (Asset) this.sessionFactory.getCurrentSession()
.createCriteria(Asset.class)
.add(Restrictions.eq("name", name))
.add(Restrictions.eq("source", source))
.uniqueResult();
}
测试班
public class AssetDaoTest {
private SessionFactory factory;
private Session session;
private Criteria criteria;
private AssetDaoImpl dao;
@Before
public void setUp() {
factory = createMock(SessionFactory.class);
session = createMock(Session.class);
criteria = createMock(Criteria.class);
dao = new AssetDaoImpl();
dao.setSessionFactory(factory);
}
@Test
public void testGetAsset() {
String name = "Test";
Source source = Source.GSFP;
Asset asset = new Asset();
asset.setName(name);
asset.setSource(source);
expect(factory.getCurrentSession()).andReturn(session);
expect(session.createCriteria(Asset.class)).andReturn(criteria);
expect(criteria.add(Restrictions.eq("name", name))).andReturn(criteria);
expect(criteria.add(Restrictions.eq("source", source))).andReturn(criteria);
expect(criteria.uniqueResult()).andReturn(asset);
replay(factory, session, criteria);
dao.getAsset(name, source);
}
}