Home » Java » JMockit: NPE while Mocking an Autowired value in the parent of the Tested clas

JMockit: NPE while Mocking an Autowired value in the parent of the Tested clas

Posted by: admin August 11, 2018 Leave a comment

Questions:

I am fairly new to JMockit, so please bear with me.
This is my class setup:

public abstract class Grandma {
    @Autowired
    Object1 obj;
    public void operation () throws Exception {
       // NPE here
       Object2 obj2 = obj.newObject();
    }
}

public abstract class Parent extends Grandma {
...
}
public class Me extends Parent {
blah 
}

So the test for Me would be:

public class MeTest extends ParentTest {
    @Tested 
    public Me meObj;

    @Injectable 
    private Object1 obj;

    @Test
    public void noSleep() {
       meObj.operation();
       new Verifications {{blah blah}};
    }
}

I get NullPointerException in that case.
So I tried using Expectations the following way (before calling operation in the test):

new Expectations {{
     obj.newObject();
     result = new Object2();
}};

I got this error instead:

java.lang.IllegalStateException: Missing invocation to mocked type at
this point; please make sure such invocations appear only after the
declaration of a suitable mock field or parameter

I also tried Deencapsulation but get a NPE while using that. On debug, I find that Object2 is still null.

What am I doing wrong ? How can I handle this case ?

Answers: