我是Mockito的新手,我已经尝试查找有关这个异常的信息,但我没有找到确切的答案。 当我同时使用两个mock时,我的代码会出现此异常,这意味着我通过一个mock的构造函数传递了另一个mock。像这样:
...
OperationNode child = getNode(Operation.ADD);
child.insertNode(getConstantNode(getIntegerValue(2));
...
private ConstantNode getConstantNode(NumericalValue value){
ConstantNode node = Mockito.mock(ConstantNode.class);
Mockito.when(node.evaluate()).thenReturn(value);
Mockito.when(node.toString()).thenReturn(value.toString());
return node;
}
private IntegerValue getIntegerValue(int number) {
IntegerValue integerValue = Mockito.mock(IntegerValue.class);
Mockito.when(integerValue.getValue()).thenReturn(number);
Mockito.when(integerValue.toString()).thenReturn(Integer.toString(number));
return integerValue;
}
在一个论坛上,我读到了关于不要通过另一个mock的构造函数发送mock的建议,因为Mockito可能会混淆mock调用,所以我尝试了以下代码:
NumericalValue value = getIntegerValue(2);
child.insertNode(getConstantNode(value));
但是没有用。我确认只有方法 toString()
和 getValue()
被调用了,因为这些是类唯一拥有的方法。我不明白发生了什么。
我还尝试着分别使用模拟对象,以查看是否有做错什么:
child.insertNode(new ConstantNode(getIntegerValue(2)));
那个完美地运作了。
child.insertNode(getConstantNode(new IntegerValue(2)));
那也可以正常工作。
https://code.google.com/p/mockito/issues/detail?id=53
- Sajan ChandranPowerMockito
的mockStatic
时遇到了异常,因为我忘记在我的测试类上添加@PrepareForTest({ClassToMock.class})
注解。 - undefined