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

时间:2015-12-16 09:59:31

标签: 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;
}

我没有写这个代码,它很难看,它完全过于复杂,但我必须使用它。

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

我以为我可以通过以下方式解决这个问题:

Mockito.when(spy.isACertainValue()).thenReturn(true);因为那是我要测试的情况。

但它仍然没有工作,因为它仍在调用方法体:/

我得到了无效指针,或者说我得到了

的内容
  

misusing.WrongTypeOfReturnValue; getValueA()不能返回Boolean。   getValueA()应该返回ValueA

所以我尝试(作为一种解决方法)来做:

Mockito.when(contextMock.getValueA()).thenReturn(new ValueA());Mockito.when(contextMock.getType()).thenReturn(ContextType.certainType);

然后我得到一个我似乎无法调试的nullpointer。

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

2 个答案:

答案 0 :(得分:21)

当您调用

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

此处调用方法isCertainValue()。这就是Java的工作原理:要评估Mockito.when的参数,必须评估spy.isCertainValue()的结果,以便必须调用该方法。

如果您不希望这种情况发生,可以使用the following construct

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

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

答案 1 :(得分:0)

此代码是正确的:

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

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

<bean id="contextMock" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="com.example.myspringproject.bean.ContextMock" />
</bean>
相关问题