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
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With