如何在不运行方法的情况下模拟方法调用和返回值?

考虑以下方法:

public boolean isACertainValue() { if(context.getValueA() != null && context.getValueA().toBoolean() == true) { if(context.getType() != null && context.getType() == ContextType.certainType) { return true; } } return false; } 

我没有写这个代码,它是丑陋的,它完全过于复杂,但我必须使用它。

现在我想测试依赖于对此方法的调用的方法。

我以为我可以通过以下方式处理:

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。

那么,在这种情况下如何正确完成?

当你调用时

 Mockito.when(spy.isCertainValue()).thenReturn(true); 

方法isCertainValue()在这里被调用。 这就是Java的工作原理:要评估Mockito.when的参数,必须对spy.isCertainValue()的结果进行求值,以便必须调用该方法。

如果您不希望发生这种情况,可以使用以下构造 :

 Mockito.doReturn(true).when(spy).isCertainValue(); 

这将具有相同的模拟效果,但不会使用此方法调用该方法。

这段代码是正确的:

 Mockito.when(contextMock.getType()).thenReturn(ContextType.certainType); 

但是你得到了NullPointerException,因为你没有定义应该定义的Mocking值,我在我的上下文文件中使用Spring,当我定义@Autowired bean时我用这种方式定义它: