【发布时间】:2015-09-24 20:39:17
【问题描述】:
我正在使用 JMockit 来测试一个正在自动装配的类(弹簧)。从这个post,我可以理解我必须手动将模拟实例注入ClassToBeTested。即使我这样做,我也会在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
}
}
【问题讨论】: