【发布时间】:2021-11-20 20:32:07
【问题描述】:
我正在使用 scalatest 和 Scala 2.x。以下编译/工作:
import org.mockito.Mockito._
import org.mockito._
import org.mockito.ArgumentMatchers._
class Test1 extends AnyFunSuite {
val action = Mockito.mock(classOf[Action])
when(action.process(anyInt())).thenReturn("x")
...
}
这不是:
import org.mockito.Mockito._
import org.mockito._
import org.mockito.ArgumentMatchers._
class Test1 extends AnyFunSuite {
@Mock
val action = Action()
when(action.process(anyInt())).thenReturn("x")
...
}
我在“何时”行收到此异常:
[info] Test1 *** ABORTED ***
[info] org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Misplaced or misused argument matcher detected here:
[info]
[info] -> at Test1.<init>(Test1.scala:17)
[info]
[info] You cannot use argument matchers outside of verification or stubbing.
[info] Examples of correct usage of argument matchers:
[info] when(mock.get(anyInt())).thenReturn(null);
[info] doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
[info] verify(mock).someMethod(contains("foo"))
[info]
[info] This message may appear after an NullPointerException if the last matcher is returning an object
[info] like any() but the stubbed method signature expect a primitive argument, in this case,
[info] use primitive alternatives.
[info] when(mock.get(any())); // bad use, will raise NPE
[info] when(mock.get(anyInt())); // correct usage use
[info]
[info] Also, this error might show up because you use argument matchers with methods that cannot be mocked.
[info] Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
[info] Mocking methods declared on non-public parent classes is not supported.
[info] at Test1.<init>(Test1.scala:17)
[info] at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[info] at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
[info] at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
[info] at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
[info] at java.lang.Class.newInstance(Class.java:442)
[info] at org.scalatest.tools.Framework$ScalaTestTask.execute(Framework.scala:450)
[info] at sbt.TestRunner.runTest$1(TestFramework.scala:140)
[info] at sbt.TestRunner.run(TestFramework.scala:155)
[info] at sbt.TestFramework$$anon$3$$anonfun$$lessinit$greater$1.$anonfun$apply$1(TestFramework.scala:318)
[info] ...
【问题讨论】: