Mockito any matcher not working for doAnswer with overloaded method

筅森魡賤 提交于 2020-01-05 07:51:13

问题


I'm trying to stub a void method from a gradle class that has 2 overloads and mockito matchers are matching the worng method and my stub is failling. Here is what I have so far:

doAnswer(new Answer<Void>() {
  @Override
  Void answer(final InvocationOnMock invocation) throws Throwable {
    Closure clo = invocation.arguments[0] as Closure
    clo.run()
    return null
  }
}).when(mProject).afterEvaluate(any(Closure.class))

But when I debugged the call to see the matcher, it was looking for the method public abstract void org.gradle.api.Project.afterEvaluate(org.gradle.api.Action) instead of public abstract void org.gradle.api.Project.afterEvaluate(groovy.lang.Closure)

Just mentioning that this is groovy not Java and I'm not sure if that has anything to do with it.

I have checked what does the any(Closure.class) matcher does ad it simply returns an null value. Supposedly the cast should make the call to the right method but for some reason it is not registering with the right method.

Any workaround accepted as well.

Thanks.


回答1:


Ok, I found this other question Unexpected behavior with overloaded methods

Apparently is groovy's fault as I have to cast the null to the correct type even if the any(Closure.class) method already returns the right type. like this:

doAnswer(new Answer<Void>() {
  @Override
  Void answer(final InvocationOnMock invocation) throws Throwable {
    Closure clo = invocation.arguments[0] as Closure
    clo.run()
    return null
  }
}).when(mProject).afterEvaluate(any(Closure.class) as Closure)


来源:https://stackoverflow.com/questions/25857019/mockito-any-matcher-not-working-for-doanswer-with-overloaded-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!