Sor*_*ona 15 java junit mockito
请考虑以下方法:
public boolean isACertainValue() {
if(context.getValueA() != null && context.getValueA().toBoolean() == true) {
if(context.getType() != null && context.getType() == ContextType.certainType) {
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
我没有写这个代码,它是丑陋的,它完全过于复杂,但我必须使用它.
现在我想测试依赖于对此方法的调用的方法.
我以为我可以通过以下方式处理:
Mockito.when(spy.isACertainValue()).thenReturn(true); 因为那是我要测试的情况.
但它不起作用,因为它仍然调用方法体:/
我得到了nullpointers,或者说我得到了一些东西
misusing.WrongTypeOfReturnValue; getValueA()不能返回Boolean.getValueA()应该返回ValueA
所以我尝试(作为一种解决方法):
Mockito.when(contextMock.getValueA()).thenReturn(new ValueA());
和
Mockito.when(contextMock.getType()).thenReturn(ContextType.certainType);
但后来我得到一个我似乎无法调试的nullpointer.
那么,在这种情况下如何正确完成?
Tun*_*aki 24
当你调用时
Mockito.when(spy.isCertainValue()).thenReturn(true);
Run Code Online (Sandbox Code Playgroud)
这个方法isCertainValue()在这里调用.这就是Java的工作原理:要评估参数Mockito.when,spy.isCertainValue()必须对结果进行求值,以便必须调用该方法.
如果您不希望发生这种情况,可以使用以下构造:
Mockito.doReturn(true).when(spy).isCertainValue();
Run Code Online (Sandbox Code Playgroud)
这将具有相同的模拟效果,但不会使用此方法调用该方法.