简体   繁体   English

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

[英]How to stub overloaded method in Mockito using Groovy?

Groovy appears to be messing up my stubbing. Groovy似乎弄乱了我的存根。 The following test passes: 以下测试通过:

MockitoStubTest2.java: 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 : 但是,这个失败了groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method ...#someMethod

MockitoStubTest3.groovy: 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. 唯一的区别是一个用Java运行,另一个用Groovy运行。

How can I make it so Mockito will successfully stub an overloaded method in Groovy? 我怎么能这样做Mockito将成功在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. 问题是Mockito匹配器方法返回null但Groovy由于某种原因搞砸了类型转换。 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: 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 我从这个类似的问题得到了答案: Mockito任何匹配器都没有使用重载方法为doAnswer工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM