Groovy appears to be messing up my stubbing. The following test passes:
MockitoStubTest2.java:
public class MockitoStubTest2 {
@Test
public void testStubbing() {
MyInterface myInterface = mock(MyInterface.class);
when(myInterface.someMethod(isA(MyClass.class))).thenReturn("foobar");
assertEquals("foobar", myInterface.someMethod(new MyClass()));
}
private interface MyInterface {
String someMethod(MyClass arg);
String someMethod(String arg);
}
private static class MyClass {}
}
However, this one fails with groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method ...#someMethod
:
MockitoStubTest3.groovy:
public class MockitoStubTest3 {
@Test
public void testStubbing() {
MyInterface myInterface = mock(MyInterface.class);
when(myInterface.someMethod(isA(MyClass.class))).thenReturn("foobar");
assertEquals("foobar", myInterface.someMethod(new MyClass()));
}
private interface MyInterface {
String someMethod(MyClass arg);
String someMethod(String arg);
}
private static class MyClass {}
}
The only difference is that one is run with Java and the other with Groovy.
How can I make it so Mockito will successfully stub an overloaded method in Groovy? This is a trivial example but I have an actual use case I need to test.
Ok I figured it out right after I posted this question... even though I've been fighting with this all day.
The problem is that the Mockito matcher methods return null
but Groovy for some reason screws up the type-cast. So you need to do the type-cast manually in order for it to find the correct method to stub. The following works:
MockitoStubTest3.groovy:
public class MockitoStubTest3 {
@Test
public void testStubbing() {
MyInterface myInterface = mock(MyInterface.class);
when(myInterface.someMethod(isA(MyClass.class) as MyClass)).thenReturn("foobar");
assertEquals("foobar", myInterface.someMethod(new MyClass()));
}
private interface MyInterface {
String someMethod(MyClass arg);
String someMethod(String arg);
}
private static class MyClass {}
}
I got the answer from this similar question: Mockito any matcher not working for doAnswer with overloaded method
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