测试方法之外的 Mockito 存根
我在测试方法之外有以下方法
I have the following method outside the test method
private DynamicBuild getSkippedBuild() {
DynamicBuild build = mock(DynamicBuild.class);
when(build.isSkipped()).thenReturn(true);
return build;
}
但是当我调用这个方法时,我得到了以下错误
but when I call this method I get the following error
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at LINE BEING CALLED FROM
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, you naughty developer!
当您在测试方法之外存根时,mockito 似乎不高兴.不支持吗?
Looks like mockito is not happy when you stub outside the test method. Is that not supported ?
我可以通过在 @Test
方法中执行存根来实现此功能,但我想在 @Test
s 中重复使用存根.
I can get this to work by doing the stubbing in @Test
method but I want to reuse the stubbing across @Test
s.
推荐答案
如果 isSkipped()
不是 final
方法,这个问题可能表明你尝试存根一种方法,而另一种方法的存根正在进行中.它不受支持,因为 Mockito 在其存根 API 中依赖于方法调用的顺序(when()
等).
If isSkipped()
is not a final
method, this problem probably indicates that you try to stub a method while stubbing of another method is in progress. It's not supported because Mockito relies on order of method invocations (when()
, etc) in its stubbing API.
我猜你的测试方法中有这样的东西:
I guess you have something like this in your test method:
when(...).thenReturn(getSkippedBuild());
如果是,则需要改写如下:
If so, you need to rewrite it as follows:
DynamicBuild build = getSkippedBuild();
when(...).thenReturn(build);
相关文章