When stubbing ClassOne.methodOne
, I'm getting the following error message about stubbing a void method with a return value, even though ClassOne.methodOne
is not void. The error seems to pertain to ClassTwo.methodTwo
, even though I'm stubbing ClassOne.methodOne
.
org.mockito.exceptions.base.MockitoException:
`'methodTwo'` is a *void method* and it *cannot* be stubbed with a *return value*!
Voids are usually stubbed with Throwables:
doThrow(exception).when(mock).someVoidMethod();
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. The method you are trying to stub is *overloaded*. Make sure you are calling
the right overloaded version.
2. Somewhere in your test you are stubbing *final methods*. Sorry, Mockito does not
verify/stub final methods.
3. A spy is stubbed using `when(spy.foo()).then()` syntax. It is safer to stub
spies with `doReturn|Throw()` family of methods. More in javadocs for
Mockito.spy() method.
My code:
public class ClassOne {
private ClassTwo classTwo;
public boolean methodOne() {
classTwo.methodTwo();
return true;
}
}
My test:
when(classOne.methodOne("some string")).thenReturn(true);
Why is this happening, and how do I fix it?