Java JMockit带弹簧的autowire不工作
我正在使用JMockit测试一个正在自动连接的类(spring)。由此,我可以理解,我将不得不手动将模拟实例注入到ClassToBeTested。即使我这样做,我也会在Java JMockit带弹簧的autowire不工作,java,spring,jmockit,Java,Spring,Jmockit,我正在使用JMockit测试一个正在自动连接的类(spring)。由此,我可以理解,我将不得不手动将模拟实例注入到ClassToBeTested。即使我这样做,我也会在Deencapsulation.setField(classUnderTest,mockSomeInterface)行中遇到NullPointerEx
Deencapsulation.setField(classUnderTest,mockSomeInterface)行中遇到NullPointerEx
因为classUnderTest和mockSomeInterface都是null
。但是,如果我在mockSomeInterface
上使用@Autowire
,它的自动连接是正确的
待测类别:
@Service
public class ClassToBeTested implements IClassToBeTested {
@Autowired
ISomeInterface someInterface;
public void callInterfaceMethod() {
System.out.println( "calling interface method");
String obj = someInterface.doSomething();
}
}
测试用例:
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
}
}
使用JMockit的最新版本尝试以下内容(注意,链接的问题来自2010年,此后该库有了很大的发展):
如何在测试类中使用spring@Autowired字段实现这一点?
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
}
}