Question

Using EasyMock 3.2, I have a test that is essentially the same as the one I have below. When I run this test there is a null pointer exception when the SUT tries to do daoSupport.getHibernateTemplate().loadAll(); When the mocked daoSupport is supposed to return the mocked template, it returns null.

@RunWith(EasyMockRunner.class)
public class DAOImplTest extends EasyMockSupport {
    @Mock
    private HibernateDaoSupport daoSupport;
    @Mock
    private HibernateTemplate template;

    @Test
    public void test() {
        expect(daoSupport.getHibernateTemplate()).andReturn(template).once(); //1
        expect(template.loadAll()).andReturn(Collections.emptyList()).once(); //2
        replayAll();

        SUT mySUT = new SUT(daoSupport);
        mySUT.exercise();
        verifyAll();
    }
}

I can get the test to work by replacing //1 in the snippet above here with

daoSupport.setHibernateTemplate(template);

Obviously this is not what I want to do. I want the mocked daoSupport to return the mocked template. What is wrong here?

Was it helpful?

Solution

The reason, as discribed in the EasyMock documentation:

Final methods cannot be mocked. If called, their normal code will be executed.

It just so happens that HibernateDaoSupport#getHibernateTemplate() is final. Since I can not change the method signature, the best I can do is to extract an interface for this class. Alternatively I can use Powermock, as mentioned in this answer.

At the end of the day, executing the normal code of the getter is not so bad. It's just a getter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top