简体   繁体   中英

Mockito issue - when(java.lang.Void) in Stubber cannot be applied to void

I can't figure out why the doNothing isn't working for this? Any ideas?

@Captor
ArgumentCaptor<GenericClass<someOtherClass>> captor;
...
Mockito.doNothing().when(mockObject.methodToStub(captor.capture()));

The error is:

Exception: when(java.lang.Void) in Stubber cannot be applied to void

This stub is wrong :

doNothing().when(mockObject.methodToStub(captor.capture())); // wrong

methodToStub(...) must be outside the when if using this API style (it should only contain the mock) :

doNothing().when(mockObject).methodToStub(captor.capture()); // correct

Tho remarks however :

  1. doNothing is the default for void methods for a mock.
  2. You can use the BDDMockito aliases that enables your code to be real à la Behavior Driven Development

Although you ask why doNothing doesn't work, I get that you actually want to capture the argument for methodToStub.

The most straightforward way to do this would be:

verify(mockObject).methodToStub(captor.capture());

If you just want you mock to do nothing at all on a void method call, remeber that doing nothing is the default for void methods on mocks.

If for some reason you still need to call doNothing , you should take care with the parentheses position. It should look like this:

doNothing().when(mockObject).methodToStub(any());

or doNothing().when(mockObject).methodToStub(captor.capture());

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