9

我在测试方法之外有以下方法

private DynamicBuild getSkippedBuild() {
    DynamicBuild build = mock(DynamicBuild.class);
    when(build.isSkipped()).thenReturn(true);
    return build;
}

但是当我调用此方法时,出现以下错误

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 不高兴。不支持吗?

编辑:我可以通过在@Test方法中执行存根来实现此功能,但我想在@Tests 中重用存根。

4

1 回答 1

15

如果isSkipped()不是final方法,则此问题可能表明您在对另一个方法进行存根时尝试存根方法。它不受支持,因为 Mockitowhen()在其存根 API 中依赖于方法调用(等)的顺序。

我猜你的测试方法中有这样的东西:

when(...).thenReturn(getSkippedBuild());

如果是这样,您需要将其重写如下:

DynamicBuild build = getSkippedBuild();
when(...).thenReturn(build);
于 2013-11-05T20:44:12.790 回答