简体   繁体   English

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

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

as the title suggests, the problem is this: I have the mock of AdesioneMerger and I have to call the real merge method.正如标题所暗示的,问题是这样的:我有AdesioneMerger的模拟,我必须调用真正的merge方法。 merge is a void method. merge是一个空方法。

This is wrong:这是错误的:

adesioneMerger = Mockito.spy(AdesioneMerger.class);

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

what's the error?有什么错误?

For void methods, use the alternative API:对于 void 方法,请使用替代 API:

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

The problem is that Mockito.when() requires an argument (and there are no void-typed arguments in Java).问题是Mockito.when()需要一个参数(Java 中没有空类型的参数)。 The alternative API works around this by calling when() on the mock type and the actual method to mock is called on the return value of when(...) .替代 API 通过在模拟类型上调用when()来解决此问题,并when() when(...)的返回值上调用要模拟的实际方法。

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

try this way:试试这个方法:

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