Ryan
Ryan

Reputation: 1331

Mockito verify method does not detect method invocation

I'm am trying to verify that a method was called on an object that I have mocked:

public class MyClass{
    public String someMethod(int arg){
        otherMethod();
        return "";
    }

    public void otherMethod(){ }
}    

public void testSomething(){
    MyClass myClass = Mockito.mock(MyClass.class);

    Mockito.when(myClass.someMethod(0)).thenReturn("test");

    assertEquals("test", myClass.someMethod(0));

    Mockito.verify(myClass).otherMethod(); // This would fail
}

This isn't my exact code, but it simulates what I am trying to do. The code would fail when trying to verify that otherMethod() was invoked. Is this correct? My understanding of the verify method is that it should detect any methods called within the stubbed method (someMethod)

I hope my question and code is clear

Upvotes: 5

Views: 14451

Answers (1)

Anders R. Bystrup
Anders R. Bystrup

Reputation: 16050

No, a Mockito mock will just return null on all invocations, unless you override with eg. thenReturn() etc.

What you're looking for is a @Spy, for example:

MyClass mc = new MyClass();
MyClass mySpy = Mockito.spy( mc );
...
mySpy.someMethod( 0 );
Mockito.verify( mySpy ).otherMethod();   // This should work, unless you .thenReturn() someMethod!

If your problem is that someMethod() contains code you don't want executed but rather mocked then inject a mock instead of mocking the method call itself, eg.:

OtherClass otherClass; // whose methods all throw exceptions in test environment.

public String someMethod(int arg){
    otherClass.methodWeWantMocked();
    otherMethod();
    return "";
}

thus

MyClass mc = new MyClass();
OtherClass oc = Mockito.mock( OtherClass.class );
mc.setOtherClass( oc );
Mockito.when( oc.methodWeWantMocked() ).thenReturn( "dummy" );

I hope that makes sense, and helps you a bit.

Cheers,

Upvotes: 4

Related Questions