[英]Mockito: mocking class always calls real method
我想模拟一堂课。
该类的调用如下:
这是我的代码:
@Mock
SomeClass someClass;
@InjectMocks
ToBeTested toBeTested;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
// in the test:
doReturn(returnValue).when(someClass).doSomething(param1, param2);
我觉得我已经尝试了@Mock
和@Spy
以及doReturn
和when
所有可能组合,但是不是doReturn
方法调用,而是调用了真正的方法并抛出了NPE。
如何正确执行此操作?
如果需要,我将提供更多代码。
编辑
SomeClass
和doSomething()
都是公共的,都不是最终的。
我尝试使用MockitoJunitRunnerclass
代替MockitoAnnotations
,但仍引发异常。
要测试的类:
@Component
public class ToBeTested implements Something {
@Override
public ReturnValue doSomeAction(Parameter theParam) {
try {
SomeClass theClass = new SomeClass();
MyReturnValue myReturnValue = theClass.doSomething(
parameterOfTypeInputStream,
parameterOfTypeString
);
// other stuff
return theParam;
} catch (IOException e) {
throw new RuntimeException("Oh no!");
}
}
// more
param1
和param2
分别为InputStream和String类型。
当然,它不是模拟的,实际的代码在doSomeAction
方法中创建真实的类,以便将模拟注入SomeClass theClass
应该是一个字段。
@Component
public class ToBeTested implements Something {
SomeClass theClass;
@Autowired
public ToBeTested(SomeClass theClass) {
this.theClass = theClass;
}
@Override
public ReturnValue doSomeAction(Parameter theParam) {
try {
MyReturnValue myReturnValue = theClass.doSomething(
parameterOfTypeInputStream,
parameterOfTypeString
);
// other stuff
return theParam;
} catch (IOException e) {
throw new RuntimeException("Oh no!");
}
}
您的应用程序容器(Spring)应该创建bean SomeClass
并将其注入,因为此构造函数由@Autowired
注释。
而且由于Mockito的@InjectMocks
批注将查找构造函数,因此它将找到该构造函数并注入您在测试类( @Mock SomeClass someClass;
)中声明的模拟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.