如何使用Groovy在Mockito中存根重载方法?

时间:2016-06-16 19:21:17

标签: java groovy mockito

Groovy似乎弄乱了我的存根。以下测试通过:

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 {}
}

但是,这个失败了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 {}
}

唯一的区别是一个用Java运行,另一个用Groovy运行。

如何使Mockito成功存在Groovy中的重载方法?这是一个简单的例子,但我有一个我需要测试的实际用例。

1 个答案:

答案 0 :(得分:5)

好的我在发布这个问题之后就把它想出来了......尽管我整天都在和这个人打架。

问题是Mockito匹配器方法返回null但Groovy由于某种原因搞砸了类型转换。因此,您需要手动进行类型转换,以便找到正确的存根方法。以下作品:

<强> 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 {}
}

我从这个类似的问题得到了答案:Mockito any matcher not working for doAnswer with overloaded method