Note that there are some explanatory texts on larger screens.

plurals
  1. POEasyMock and Hibernate Criteria Queries
    text
    copied!<p>I am trying to test a dao method which uses the hibernate criteria API, using JUnit4 and EasyMock 2.4. </p> <p>When I run the test fixture 'testGetAsset' I receive the following exception:</p> <pre><code>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) </code></pre> <p>I think the problem is related to the mock criteria object not being initialized with Asset.class, but I'm quite a beginner with EasyMock and mock objects in general, so I'd really appreciate it if someone could take a look and tell me what I need to do to make the test pass.</p> <p>Many thanks, Mark</p> <p>Code is below:</p> <h2>Dao Method</h2> <pre><code>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(); } </code></pre> <h2>Test Class</h2> <pre><code>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); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload