2012-02-21 2 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(){ 
     } 
    } 
} 

Этот тест в 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) 

наблюдается ли anymone такая же ошибка?

ответ

8

Проблема: Groovy перехватывает вызов метода до достижения someVoidMethod. Фактически вызываемый метод равен getMetaClass, который не является методом void.

Вы можете проверить, что это происходит путем замены:

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

с:

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

Я не уверен, что вы будете в состоянии обойти эту проблему с помощью акций Mockito и Groovy.

+0

Что следует использовать тогда? У меня такая же проблема, и я застрял с ней. – Guillaume

+0

Вы можете попробовать [mockito-groovy-support] (https://github.com/cyrusinnovation/mockito-groovy-support). Он решил проблему getMetaClass() для меня – csab

Смежные вопросы