Sorona Sorona - 2 months ago 14
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();

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

@Test
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
someOtherMethod()
.
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
someOtherMethod(...)
has a non-void return-value here. But imagine the return value was
void
...

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

Answer

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.

Comments