我是Mockito的新手。我正在使用mockito 1.9.5。与eclipse kepler一起提供的junit 4。 当我在下面的junit中运行这个测试时。
<pre><code>
@SuppressWarnings("rawtypes")
@Test
public void stubbingCallbacks(){
when(mockedList.add(anyString())).thenAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
//Object mock = invocation.getMock();
return "called with arguments: " + args;
}
});
System.out.println(mockedList.add("a"));
}
</code></pre>
然后它抛出了我这个例外
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
at $java.util.LinkedList$$EnhancerByMockitoWithCGLIB$$2744633c.add()
at com.mock.Verifying.stubbingCallbacks(Verifying.java:185)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
有谁知道为什么会抛出ClassCastException?和 我该如何解决这个问题?
非常感谢你的帮助
苏拉
答案 0 :(得分:1)
当然可以:List.add(item)
返回boolean
,您的回答会返回String
。
答案 1 :(得分:0)
无法违反您所嘲笑的方法的返回类型。 mockedList.add()
的返回值是布尔值,因此你的mock也应该是布尔值而不是"called with arguments: " + args