2012-02-21 93 views
5

我正在使用Mockito 1.9和Grails 1.3.7,我有一個奇怪的錯誤。Mockito中的錯誤與Grails/Groovy

下面的測試案例中的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(){ 
     } 
    } 
} 

該測試在常規不起作用:

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) 

是否anymone觀察同樣的錯誤?

回答

8

問題是Groovy在達到someVoidMethod之前攔截了您的方法調用。實際調用的方法是getMetaClass,這不是一種無效的方法。

您可以驗證這是通過更換髮生:

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

有:

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

我不知道,你將能夠用股票Mockito和Groovy來解決這個問題。

+0

那我該用什麼?我有同樣的問題,我堅持下去。 – Guillaume 2015-01-06 16:01:53

+0

你可以試試[mockito-groovy-support](https://github.com/cyrusinnovation/mockito-groovy-support)。它爲我解決了getMetaClass()問題 – csab 2016-08-19 02:42:03