[英]Mockito counting stubbing as invocation
Trying to stub a class with 2 possible invocation/return paths using custom Matcher ... ran into an interest problem. 试图使用自定义Matcher对具有2种可能的调用/返回路径的类进行存根...遇到了兴趣问题。
Here is a test I wrote to illustrate ... 这是我写来说明的测试...
This might be difficult to implement, but I would have expected the 1st ArgumentMatcher
is not invoked when stubbing the second when(...).thenReturn(...)
这可能很难实现,但是我希望在对第二个
when(...).thenReturn(...)
存根处理when(...).thenReturn(...)
不会调用第一个ArgumentMatcher
when(...).thenReturn(...)
But running the code below prints foobar
on stdout. 但是运行下面的代码会在stdout上打印
foobar
。 Is there anything we can do to prevent this behavior? 我们有什么办法可以防止这种行为? Or am I using the wrong pattern by trying to stub a single mock with multiple custom
ArgumentMatcher
还是我尝试通过使用多个自定义
ArgumentMatcher
存根单个模拟来使用错误的模式
FYI - powermock
is on my classpath for other tests (not sure if that matters but I do see it in the stack trace) 仅供参考
powermock
在我的类路径中用于其他测试(不确定是否很重要,但是我确实在堆栈跟踪中看到了它)
import org.junit.Test;
import org.mockito.ArgumentMatcher;
import java.io.File;
import java.io.FilenameFilter;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MyTest {
@Test
public void name() throws Exception {
File file = mock(File.class);
when(file.list(argThat(new ArgumentMatcher<FilenameFilter>() {
@Override
public boolean matches(Object argument) {
System.out.println("foobar");
return 1 + 1 >2;
}
}))).thenReturn(null);
// at this point, mockito will attempt to run the previous matcher, treating this stub code as invocation ... and printing out 'foobar'
when(file.list(argThat(new ArgumentMatcher<FilenameFilter>() {
@Override
public boolean matches(Object argument) {
System.out.println("barbar");
return true;
}
}))).thenReturn(null);
}
}
EDIT added comments to help illustrate 编辑添加注释以帮助说明
If you use the doReturn()
syntax, then the method is not called. 如果使用
doReturn()
语法,则不会调用该方法。
doReturn(null).when(file).list(argThat(new ArgumentMatcher<FilenameFilter>() {
@Override
public boolean matches(Object argument) {
System.out.println("barbar");
return true;
}
}));
See this answer for more details. 有关更多详细信息,请参见此答案 。 Also, the docs explain this use-case (emphasis mine):
此外, 文档还解释了这个用例(重点是我的):
You can use doReturn(), [...] in place of the corresponding call with when(), for any method.
对于任何方法,都可以使用doReturn(),[...]代替when()的相应调用。 It is necessary when you:
当您:
- stub void methods
存根无效方法
- stub methods on spy objects (see below)
间谍对象的存根方法(请参见下文)
- stub the same method more than once, to change the behaviour of a mock in the middle of a test.
多次对同一方法进行存根测试,以在测试过程中更改模拟的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.