Search code examples
javaspringjmockit

JMockit with Spring autowire not working


I'm using JMockit to test a class which is being autowired (spring). From this post, i could understand that i will have to manually inject the mock instance to the ClassToBeTested. Even if i do this, i'm running into NullPointerEx at line Deencapsulation.setField(classUnderTest, mockSomeInterface); since both classUnderTest and mockSomeInterface are null. However if i use @Autowire on mockSomeInterface, it's being auto wired properly.

Class To Be tested:

@Service
public class ClassToBeTested implements IClassToBeTested {

 @Autowired
 ISomeInterface someInterface;

 public void callInterfaceMethod() {
  System.out.println( "calling interface method");
  String obj = someInterface.doSomething();
 }
}

Test Case:

public class ClassToBeTestedTest  {

@Tested IClassToBeTested classUnderTest;

@Mocked ISomeInterface mockSomeInterface;

public void testCallInterfaceMethod(){
  Deencapsulation.setField(classUnderTest, mockSomeInterface);
  new Expectations() { {
     mockSomeInterface.doSomething(anyString,anyString); result="mock data";     
  }};
 // other logic goes here
 }
}

Solution

  • Try the following, using a recent version of JMockit (note the linked question is from 2010, and the library has evolved a lot since then):

    public class ClassToBeTestedTest
    {
        @Tested ClassToBeTested classUnderTest;
        @Injectable ISomeInterface mockSomeInterface;
    
        @Test
        public void exampleTest() {
            new Expectations() {{
                mockSomeInterface.doSomething(anyString, anyString); result = "mock data";
            }};
    
            // call the classUnderTest
        }
    }