简体   繁体   中英

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. merge is a void method.

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:

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). 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(...) .

See also this answer: 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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