Sorona Sorona - 1 year ago 103
Java Question

Mockito says "Wanted but not invoked" but debugging test jumps into that method

I have to deal with a legacy application that has no tests. So before I begin refactoring I want to make sure everything works as it is.

Now imagine the following situation:

public SomeObject doSomething(final OtherObject x, final String something) {
if(x != null) {
final String = someOtherMethod(x, something);

protected String someOtherMethod(final OtherObject x, final String something) {

Now I want to make sure that protected method is called as well

So I did this

@InjectMocks // Yes there is more going on here
private MyTestObject myTestObject;

private MyTestObject spy;

private static final OtherObject VALID_OTHER_OBJECT = new OtherObject();

public void setup() {
this.spy = Mockito.spy(myTestObject);

public void ifOtherObjectIsNotNullExpectSubMethodToBeCalled() {
myTestObject.doSomething(VALID_OTHER_OBJECT, null);
verify(spy).someOtherMethod(VALID_OTHER_OBJECT, null);

I get a failing test and "Wanted but not invoked..." for
I jumped right into debug mode and checked. That method is called!

What could be the cause of this? Am I misusing the spy here?

Edit: I want to stretch that I know this is not what you typically test for, especially since
has a non-void return-value here. But imagine the return value was

Basically I just want to understand why the spy fails here.

Answer Source

As per its Javadoc, Mockito.spy(object) creates a copy of the passed in object. Calling methods on the original passed in object then does not register on the spy, because the spy instance is not the same object.

Change myTestObject.doSomething(...) to spy.doSomething(...) and it should work.

Alternative (different way to achieve the same thing): Consider using the @Spy annotation on your myTestObject. Be sure to add MockitoAnnotations.initMocks(this); to your initialization method (in your junit test). The @Before and @Mock annotations are useful as well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download