I am trying to mock a DAO with JMockit:
public interface MyDao {
Details getDetailsById(int id);
}
With this test class:
public class TestClass {
@Test
public void testStuff(final MyDao dao) throws Exception
{
new Expectations()
{
{
// when we try to get the message details, return our sample
// details
dao.getDetailsById((Integer) any); ***THROWS AN NPE
result = sampleDetails;
}
};
ClassUsingDao daoUser = new ClassUsingDao(dao);
// calls dao.getDetailsById()
daoUser.doStuff();
}
When the dao object is used in the Expectations block, an NPE is thrown. I’ve tried moving the declaration of dao to a member variable annotated with @Mocked, but the same thing happens. I’ve also tried using a concrete implementation of MyDao, and the same thing happens.
It’s not
daothat’s null, butany. The unboxing from Integer (after your cast) to int involves a dereference, which throws a NullPointerException. Try usinganyIntinstead.I don’t think the jMockit documentation talks about what the actual value of Expectations.any is, but note that it can be successfully cast to any other type (you can say
(String)anyand(Integer)any). The only value in Java for which all casts will always succeed isnull. So, Expectations.any must be null. Bit of a surprise, but inevitable really.