java 创建某种对象类型的 Mockito 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28184179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create Mockito Array of some Object type
提问by iPhoneJavaDev
I need to provide some mock object array of this type "TypeA[]".
我需要提供一些这种“TypeA[]”类型的模拟对象数组。
I am trying to do this but getting classcastexception:
我正在尝试这样做,但收到 classcastexception:
List mockList = Mockito.anyListOf(TypeA.class);
when(someService.create(Mockito.any(TypeB.class), (TypeA[])mockList.toArray())).thenReturn(1);
采纳答案by Dongqing
The error message told you clearly :
错误信息清楚地告诉你:
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(anyObject());
verify(mock).someMethod(contains("foo"))
The method call to object returned by Mockito.anyListOfcan only inside stubbing or verification .
Mockito.anyListOf返回的对象的方法调用只能在stubbing或verify中进行。
you can simply do that to mock array :
你可以简单地这样做来模拟数组:
when(mockTest.create(any(TypeB.class), any(TypeA[].class))).thenReturn(1);