gpt4 book ai didi

java - 是否可以使用mockito 实现单个 void 方法的主体?

转载 作者:行者123 更新时间:2023-12-02 05:45:50 25 4
gpt4 key购买 nike

我想使用 Mockito 重写类的单个 void 方法的实现。其他方法应该被 stub 。

我尝试过类似的方法,但它无法编译,因为 java.lang.Void != void:

MyObj obj = mock(MyObj.class);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
return null;
}
}).when(obj.myMethod(any(String.class)));

没有“doInvoke”或类似的东西吗?

在模拟扩展类之前我必须求助于标准 Java 类扩展和覆盖吗?

最佳答案

来自the documentation :

Stubbing voids requires different approach from when(Object) because the compiler does not like void methods inside brackets...

doThrow(Throwable) replaces the stubVoid(Object) method for stubbing voids. The main reason is improved readability and consistency with the family of doAnswer() methods.

You can use doThrow(), doAnswer(), doNothing(), doReturn() and doCallRealMethod() in place of the corresponding call with when(), for any method. 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.

but you may prefer to use these methods in place of the alternative with when(), for all of your stubbing calls.

所以听起来你只是想要:

doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
return null;
}
}).when(obj).myMethod(any(String.class));

关于java - 是否可以使用mockito 实现单个 void 方法的主体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24081928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com