0

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.

Tom Anderson
  • 46,189
  • 17
  • 92
  • 133
Brian
  • 2,375
  • 4
  • 24
  • 35
  • No, Spring isn't currently used in this class, but probably will be used to inject dao into ClassUsingDao in the future. – Brian Jul 31 '11 at 16:45

1 Answers1

2

It's not dao that's null, but any. The unboxing from Integer (after your cast) to int involves a dereference, which throws a NullPointerException. Try using anyInt instead.

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)any and (Integer)any). The only value in Java for which all casts will always succeed is null. So, Expectations.any must be null. Bit of a surprise, but inevitable really.

Tom Anderson
  • 46,189
  • 17
  • 92
  • 133
  • Sure enough, that was it. Thanks for the help - I've spent hours moving that around and it was right in front of me. Thanks! – Brian Jul 31 '11 at 16:52