Search code examples
javaunit-testinginheritancejmockit

JMockit test class inheritance: mocked fields not injected when declared in parent class


I have test class inheritance issue: putting @Mocked and @Injectable fields to common abstract test parent class breaks auto-injection of mocked instances to @Tested class. I use JMockit 1.5. Here's an example:

public MyService {

    private MyStorage storage;

    public void myMethod(String entityId){
        storage.getEntity(entityId);

        // ...
    }
}

public abstract class AbstractTestBase {
    @Injectable
    protected MyStorage storage;
}

public class MyTest extends AbstractTestBase {

    @Tested
    private MyService tested;

    @Test
    public void test_myMethod(){

         new Expectations() {
        {
            storage.getEntity("1");
            result = "foobar";
        }

        tested.myMethod("1");   // <-- here I have NPE 
                                // as storage is not injected properly.

        // ...
    };
    }
}

If I move @Injectable MyStorage storage to MyTest class everything gets injected correctly to @Tested class.

How can I allow auto-injections with common parent for test classes?


Solution

  • I found out the issue is solved in the most up to date release 1.11.