繁体   English   中英

Mockito、mock 类和真正调用 void 方法

[英]Mockito, mock class and real call void Methods

正如标题所暗示的,问题是这样的:我有AdesioneMerger的模拟,我必须调用真正的merge方法。 merge是一个空方法。

这是错误的:

adesioneMerger = Mockito.spy(AdesioneMerger.class);

Mockito.when(adesioneMerger.merge(
    Matchers.any(AdesioneBean.class),
    Matchers.any(Adesione.class), 
    Matchers.any(ServiceResultBean.class))
).ThenCallRealMethod();

有什么错误?

对于 void 方法,请使用替代 API:

Mockito.doCallRealMethod()
  .when(adesioneMerger).merge(
     Matchers.any(AdesioneBean.class),
     Matchers.any(Adesione.class), 
     Matchers.any(ServiceResultBean.class));

问题是Mockito.when()需要一个参数(Java 中没有空类型的参数)。 替代 API 通过在模拟类型上调用when()来解决此问题,并when() when(...)的返回值上调用要模拟的实际方法。

另请参阅此答案: How to make mock to void methods with mockito

试试这个方法:

doCallRealMethod().when(adesioneMerger).merge(
    Matchers.any(AdesioneBean.class),
    Matchers.any(Adesione.class), 
    Matchers.any(ServiceResultBean.class);

暂无
暂无

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

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