加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

单元测试 – 使用Grails / Groovy的Mockito中的错误

发布时间:2020-12-14 16:25:32 所属栏目:大数据 来源:网络整理
导读:我使用Grails 1.3.7的Mockito 1.9,我有一个奇怪的错误. 以下java中的测试用例: import static org.mockito.Mockito.*;public class MockitoTests extends TestCase { @Test public void testSomeVoidMethod(){ TestClass spy = spy(new TestClass()); doNot
我使用Grails 1.3.7的Mockito 1.9,我有一个奇怪的错误.

以下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()

我不确定你是否能够使用库存Mockito和Groovy解决这个问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读