Is it possible to a single void method's body with mockito?

I want to override the implementation of a single void method of a class using Mockito. The other methods should be stubbed.

I have tried something like this, but it does not compile since 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)));

Is there no "doInvoke" or something like that?

Must I resort to standard Java class extend-and-override before mocking the extended class?

Jon Skeet
people
quotationmark

From 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.

So it sounds like you just want:

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

people

See more on this question at Stackoverflow