Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stub overloaded method in Mockito using Groovy?

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.

like image 696
tytk Avatar asked Jun 16 '16 19:06

tytk


1 Answers

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

like image 177
tytk Avatar answered Oct 31 '22 16:10

tytk