unit-testing - 使用 Grails/Groovy 的 Mockito 中的错误

标签 unit-testing grails groovy mockito

我将 Mockito 1.9 与 Grails 1.3.7 一起使用,但我有一个奇怪的错误。

java中的以下测试用例有效:

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 中的此测试不起作用:

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)

有没有人观察到同样的错误?

最佳答案

问题是 Groovy 在到达 someVoidMethod 之前拦截了您的方法调用.实际调用的方法是 getMetaClass这不是 void 方法。

您可以通过替换以下内容来验证是否发生了这种情况:

doNothing().when(testClassMock).someVoidMethod()

和:
doReturn(testClassMock.getMetaClass()).when(testClassMock).someVoidMethod()

我不确定您是否能够使用 stock Mockito 来解决这个问题。和 Groovy。

关于unit-testing - 使用 Grails/Groovy 的 Mockito 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9375356/

相关文章:

objective-c - 为什么我不能多次在 Typhoon 中设置默认工厂?

Python:单元测试中的模拟

ios - XCTest 错误 : The bundle couldn’t be loaded. 尝试重新安装 bundle

eclipse - STS-建立保存

grails - 为什么在 intelliJ 中构建 grails 时会收到许多重复的编译消息

java - 使用 Groovy 解压缩存档

orm - 独立使用 Grails GORM

unit-testing - 为什么 `assert_eq` 和 `assert_ne` 存在,而简单的 `assert` 就足够了?

grails - Grails-包括CAS客户端JAR依赖项会导致StackOverflowError,日志记录冲突?

java - 字符串到日期转换的问题