java Mockito - 当然后返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45222786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mockito - when thenReturn
提问by Paz
I'm new to the Mockito library and I can't understand the following syntax: before the test I defined -
我是 Mockito 库的新手,无法理解以下语法:在我定义的测试之前 -
when(CLASS.FUNCTION(PARAMETERS)).thenReturn(RETURN_VALUE)
And the actual test is -
实际测试是——
assertSame(RETURN_VALUE, CLASS.FUNCTION(PARAMETERS))
Don't I just set the return value of the function with the first line of code (when... thenReturn
) to be RETURN_VALUE
? If the answer is yes, then of course assertSame
will be true and the test will pass, what am I missing here?
我不是只是将第一行代码 ( when... thenReturn
)的函数的返回值设置为RETURN_VALUE
?如果答案是肯定的,那么当然assertSame
会是真的并且测试会通过,我在这里错过了什么?
回答by Mureinik
The point of Mockito (or any form of mocking, actually) isn't to mock the code you're checking, but to replace external dependencies with mocked code.
Mockito(或任何形式的模拟,实际上)的重点不是模拟您正在检查的代码,而是用模拟代码替换外部依赖项。
E.g., consider you have this trivial interface:
例如,假设您有这个简单的界面:
public interface ValueGenerator {
int getValue();
}
And this is your code that uses it:
这是您使用它的代码:
public class Incrementor {
public int increment(ValueGenerator vg) {
return vg.getValue() + 1;
}
}
You want to test your Incrementor
logic without depending on any sepecific implementation of ValueGenerator
.
That's where Mockito comes into play:
您想在Incrementor
不依赖于ValueGenerator
. 这就是 Mockito 发挥作用的地方:
// Mock the dependencies:
ValueGenerator vgMock = Mockito.mock(ValueGenerator.class);
when(vgMock.getValue()).thenReturn(7);
// Test your code:
Incrementor inc = new Incrementor();
assertEquals(8, inc.increment(vgMock));