简体   繁体   English

Mockito在测试方法之外存根

[英]Mockito stubbing outside of the test method

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!

Looks like mockito is not happy when you stub outside the test method. 当你在测试方法之外存在时,看起来mockito不高兴。 Is that not supported ? 这不受支持吗?

EDIT: I can get this to work by doing the stubbing in @Test method but I want to reuse the stubbing across @Test s. 编辑:我可以通过@Test方法中的存根来实现这一点,但我想重用@Test的存根。

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. 如果isSkipped()不是final方法,则此问题可能表示您尝试在另一个方法的存根正在进行时存根方法。 It's not supported because Mockito relies on order of method invocations ( when() , etc) in its stubbing API. 它不受支持,因为Mockito依赖于其存根API中的方法调用顺序( when()等)。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM