groovy 在spock中模拟静态方法时偶尔会出错

yacmzcpb  于 2022-12-11  发布在  其他
关注(0)|答案(1)|浏览(313)

我为同一个工具类方法编写了两个测试类(CryptUtilTest1.groovy、CryptUtilTest2.groovy),我模拟了CryptUtilTest2.groovy中的StringImplUtils.emptyIfBlank方法,当两个测试类分别执行时,测试类都能正常执行,但是当两个测试用例一起执行时,第二个测试类有时会出现如下错误:

> Task :CallServer:compileJava UP-TO-DATE
> Task :CallServer:compileGroovy NO-SOURCE
> Task :CallServer:processResources UP-TO-DATE
> Task :CallServer:classes UP-TO-DATE
> Task :CallServer:compileTestJava NO-SOURCE
> Task :CallServer:compileTestGroovy
> Task :CallServer:processTestResources UP-TO-DATE
> Task :CallServer:testClasses
> Task :CallServer:test
[INFO] TestableMock start at E:\isouceWork\VRBT_RCPA_V100R001C10\JAVA_CODE\CallServer


Misplaced or misused argument matcher detected here:

-> at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(any());
    verify(mock).someMethod(contains("foo"))

This message may appear after an NullPointerException if the last matcher is returning an object 
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
    when(mock.get(any())); // bad use, will raise NPE
    when(mock.get(anyInt())); // correct usage use

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Misplaced or misused argument matcher detected here:

-> at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(any());
    verify(mock).someMethod(contains("foo"))

This message may appear after an NullPointerException if the last matcher is returning an object 
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
    when(mock.get(any())); // bad use, will raise NPE
    when(mock.get(anyInt())); // correct usage use

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.

    at com.huawei.callserver.utils.CryptUtilTest2.test(CryptUtilTest2.groovy:22)
    Suppressed: java.lang.NullPointerException: Cannot invoke method close() on null object
        at org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:91)
        at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:44)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
        at org.codehaus.groovy.runtime.callsite.NullCallSite.call(NullCallSite.java:34)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:130)
        at com.huawei.callserver.utils.CryptUtilTest2.$spock_feature_0_0(CryptUtilTest2.groovy:29)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.spockframework.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:198)
        at org.spockframework.runtime.model.MethodInfo.lambda$new$0(MethodInfo.java:47)
        at org.spockframework.runtime.model.MethodInfo.invoke(MethodInfo.java:148)
        at org.spockframework.runtime.PlatformSpecRunner.invokeRaw(PlatformSpecRunner.java:409)
        at org.spockframework.runtime.PlatformSpecRunner.invoke(PlatformSpecRunner.java:392)
        at org.spockframework.runtime.PlatformSpecRunner.runFeatureMethod(PlatformSpecRunner.java:326)
        at org.spockframework.runtime.IterationNode.execute(IterationNode.java:48)
        at org.spockframework.runtime.SimpleFeatureNode.execute(SimpleFeatureNode.java:58)
        at org.spockframework.runtime.SimpleFeatureNode.execute(SimpleFeatureNode.java:15)
        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
        at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
        at org.spockframework.runtime.SpockNode.sneakyInvoke(SpockNode.java:40)
        at org.spockframework.runtime.IterationNode.lambda$around$0(IterationNode.java:63)
        at org.spockframework.runtime.PlatformSpecRunner.lambda$createMethodInfoForDoRunIteration$5(PlatformSpecRunner.java:238)
        at org.spockframework.runtime.model.MethodInfo.invoke(MethodInfo.java:148)
        at org.spockframework.runtime.PlatformSpecRunner.invokeRaw(PlatformSpecRunner.java:409)
        at org.spockframework.runtime.PlatformSpecRunner.invoke(PlatformSpecRunner.java:392)
        at org.spockframework.runtime.PlatformSpecRunner.runIteration(PlatformSpecRunner.java:220)
        at org.spockframework.runtime.IterationNode.around(IterationNode.java:63)
        at org.spockframework.runtime.SimpleFeatureNode.lambda$around$0(SimpleFeatureNode.java:52)
        at org.spockframework.runtime.SpockNode.sneakyInvoke(SpockNode.java:40)
        at org.spockframework.runtime.FeatureNode.lambda$around$0(FeatureNode.java:29)
        at org.spockframework.runtime.PlatformSpecRunner.lambda$createMethodInfoForDoRunFeature$4(PlatformSpecRunner.java:201)
        at org.spockframework.runtime.model.MethodInfo.invoke(MethodInfo.java:148)
        at org.spockframework.runtime.PlatformSpecRunner.invokeRaw(PlatformSpecRunner.java:409)
        at org.spockframework.runtime.PlatformSpecRunner.invoke(PlatformSpecRunner.java:392)
        at org.spockframework.runtime.PlatformSpecRunner.runFeature(PlatformSpecRunner.java:194)
        at org.spockframework.runtime.FeatureNode.around(FeatureNode.java:29)
        at org.spockframework.runtime.SimpleFeatureNode.around(SimpleFeatureNode.java:52)
        at org.spockframework.runtime.SimpleFeatureNode.around(SimpleFeatureNode.java:15)
        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
        at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
        at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
        at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
        at java.util.ArrayList.forEach(ArrayList.java:1257)
        at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
        at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
        at org.spockframework.runtime.SpockNode.sneakyInvoke(SpockNode.java:40)
        at org.spockframework.runtime.SpecNode.lambda$around$0(SpecNode.java:63)
        at org.spockframework.runtime.PlatformSpecRunner.lambda$createMethodInfoForDoRunSpec$0(PlatformSpecRunner.java:61)
        at org.spockframework.runtime.model.MethodInfo.invoke(MethodInfo.java:148)
        at org.spockframework.runtime.PlatformSpecRunner.invokeRaw(PlatformSpecRunner.java:409)
        at org.spockframework.runtime.PlatformSpecRunner.invoke(PlatformSpecRunner.java:392)
        at org.spockframework.runtime.PlatformSpecRunner.runSpec(PlatformSpecRunner.java:55)
        at org.spockframework.runtime.SpecNode.around(SpecNode.java:63)
        at org.spockframework.runtime.SpecNode.around(SpecNode.java:11)
        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
        at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
        at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
        at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
        at java.util.ArrayList.forEach(ArrayList.java:1257)
        at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
        at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
        at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
        at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
        at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
        at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
        at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
        at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
        at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
        at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
        at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
        at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
        at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
        at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
        at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
        at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
        at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
        at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
        at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
        at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
        at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
        at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
        at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
        at com.sun.proxy.$Proxy2.stop(Unknown Source)
        at org.gradle.api.internal.tasks.testing.worker.TestWorker$3.run(TestWorker.java:193)
        at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
        at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
        at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
        at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
        at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
        at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
        at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
        at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)

Condition not satisfied:

"123" == CryptUtil.test("123")
      |  |         |
      |  |         null
      |  class com.huawei.callserver.utils.CryptUtil
      false

Condition not satisfied:

"123" == CryptUtil.test("123")
      |  |         |
      |  |         null
      |  class com.huawei.callserver.utils.CryptUtil
      false

    at com.huawei.callserver.utils.CryptUtilTest2.test1(CryptUtilTest2.groovy:35)

CryptUtilTest2 > test FAILED
    org.mockito.exceptions.misusing.InvalidUseOfMatchersException at CryptUtilTest2.groovy:22
CryptUtilTest2 > test1 FAILED
    org.spockframework.runtime.SpockComparisonFailure at CryptUtilTest2.groovy:35
7 tests completed, 2 failed
> Task :CallServer:test FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':CallServer:test'.
> There were failing tests. See the report at: file:///E:/isouceWork/VRBT_RCPA_V100R001C10/JAVA_CODE/CallServer/build/reports/tests/test/index.html
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.2/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 17s
5 actionable tasks: 2 executed, 3 up-to-date

两个测试类单独结果如下所示:

一月一日

一个月一个月

gradle.build

testImplementation 'org.codehaus.groovy:groovy-all:3.0.7'
testImplementation group: 'org.spockframework', name: 'spock-core', version: '2.0-groovy-3.0'
testImplementation group: 'org.spockframework', name: 'spock-spring', version: '2.0-groovy-3.0'
testImplementation group: 'org.mockito', name: 'mockito-inline', version: '4.9.0'

我的测试代码:
第一个
当我使用spock1.*+powermock进行测试时,这种概率错误并没有发生。

iqih9akk

iqih9akk1#

当按以下顺序一起执行测试时,我可以重现问题:

  1. CryptUtilTest1
  2. CryptUtilTest2
    如果在第一个测试中避免使用Mockito.anyString(),问题也会消失,因为第一个测试实际上并不是Mockito测试,该方法返回"",所以你可以在第一次测试中用""或者"dummy"来替换它,这样测试就通过了。s any*()方法旨在用于mockito匹配器表达式内部,例如类似verify(mock).someMethod(anyInt(), anyString(), eq("third argument"));的表达式。

相关问题