使用Groovy类的@Spy编写Mockito单元测试时出错,该类扩展了抽象类

问题描述

当对Mockito类使用Unit运行@Spy Groovy测试来扩展abstract类时,我遇到一个问题。如果删除abstract或将父类创建为常规Java类,则不会发生此错误。可能是什么问题?

    abstract class ClassA
    {
    }
    
    @Component
    class ClassB extends ClassA
    {
        void validateBeforeCreate(String arg1,Object arg2)
        {
            check(arg1,arg2)
        }
    
        protected void check(String arg1,Object arg2)
        {
            // some validation logic
        }
    }
    
    @ExtendWith(MockitoExtension)
    class ClassBTest
    {
        @Spy
        @InjectMocks
        private ClassB classB
    
        @Test
        void testValidateBeforeCreate_Success()
        {
            String arg1 = "test"
            Object arg2 = new Object()
    
            donothing().when(classB).check(arg1,arg2)
    
            assertDoesNotthrow({ classB.validateBeforeCreate(arg1,arg2) } as Executable)
        }
    }

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:146)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallSite(CallSiteArray.java:163)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:115)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:135)
    at com.tr.cws.workflow.trigger.test.ClassBTest.testValidateBeforeCreate_Success(ClassBTest.groovy:25)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)