Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito verify method does not detect method invocation

Tags:

java

mockito

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

like image 949
Ryan Avatar asked Oct 06 '22 03:10

Ryan


1 Answers

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,

like image 122
Anders R. Bystrup Avatar answered Oct 10 '22 01:10

Anders R. Bystrup