是否可以使用Mockito的doCallRealMethod调用接口的默认实现?

rab*_*ens 7 mockito

假设我有以下界面:

public interface ISomething {

    default int doStuff() {
        return 2 * getValue();
    }

    int getValue();
}
Run Code Online (Sandbox Code Playgroud)

当我现在模仿这个界面时:

@Mock
private ISomething _something;

@Before
public void setup() {
    doCallRealMethod().when(_something).doStuff();
}
Run Code Online (Sandbox Code Playgroud)

并尝试测试doStuff()方法,如下所示:

@Test
public void testDoStuff() {
    when(_something.getValue()).thenReturn(42);
    assertThat("doStuff() returns 84", _something.doStuff(), is(84));
}
Run Code Online (Sandbox Code Playgroud)

我希望测试成功,但我得到:

org.mockito.exceptions.base.MockitoException:
Cannot call real method on java interface. Interface does not have any implementation!
Calling real methods is only possible when mocking concrete classes.
Run Code Online (Sandbox Code Playgroud)

我尝试ISomething使用这样的抽象类进行子类化:

public abstract class Something implements ISomething {
}
Run Code Online (Sandbox Code Playgroud)

像上面那样嘲笑这个类.通过这种方法,我得到了同样的结果.

Mockito不支持调用默认实现吗?

Daw*_*ica 3

这是正确的。当前版本的 Mockito 不支持此功能。您可以在此处提出功能请求。请注意,它似乎与 1.10.0 版本中修复的问题 456 有关,因此请确保先在最新版本中进行测试。