带有 Grails/Groovy 的 Mockito 中的错误 [英] Bug in Mockito with Grails/Groovy
问题描述
我将 Mockito 1.9 与 Grails 1.3.7 一起使用,但我遇到了一个奇怪的错误.
I am using Mockito 1.9 with Grails 1.3.7 and I have a strange bug.
java 中的以下测试用例有效:
The following test case in java works:
import static org.mockito.Mockito.*;
public class MockitoTests extends TestCase {
@Test
public void testSomeVoidMethod(){
TestClass spy = spy(new TestClass());
doNothing().when(spy).someVoidMethod();
}
public static class TestClass {
public void someVoidMethod(){
}
}
}
这个在 groovy 中的测试不起作用:
This test in groovy does not work:
import static org.mockito.Mockito.*
public class MockitoTests extends TestCase {
public void testSomeVoidMethod() {
def testClassMock = spy(new TestClass())
doNothing().when(testClassMock).someVoidMethod()
}
}
public class TestClass{
public void someVoidMethod(){
}
}
这是错误信息:
only void methods can doNothing()!
Example of correct use of doNothing():
doNothing().
doThrow(new RuntimeException())
.when(mock).someVoidMethod();
Above means:
someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called
org.mockito.exceptions.base.MockitoException:
Only void methods can doNothing()!
Example of correct use of doNothing():
doNothing().
doThrow(new RuntimeException())
.when(mock).someVoidMethod();
Above means:
someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called
at org.codehaus.groovy.runtime.callsite.CallSiteArray.createPogoSite(CallSiteArray.java:129)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallSite(CallSiteArray.java:146)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
有没有人发现同样的错误?
Does anymone observed the same error?
推荐答案
问题是 Groovy 在你的方法调用到达 someVoidMethod
之前拦截了它.实际调用的方法是 getMetaClass
,它不是 void 方法.
The problem is Groovy is intercepting your method call before it reaches someVoidMethod
. The method actually being called is getMetaClass
which is not a void method.
您可以通过替换来验证这是否正在发生:
You can verify this is happening by replacing:
doNothing().when(testClassMock).someVoidMethod()
与:
doReturn(testClassMock.getMetaClass()).when(testClassMock).someVoidMethod()
我不确定您是否能够使用股票 Mockito
和 Groovy 解决此问题.
I'm not sure you will be able to get around this issue using stock Mockito
and Groovy.
这篇关于带有 Grails/Groovy 的 Mockito 中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!