创建某种对象类型的 Mockito 数组

Create Mockito Array of some Object type

我需要提供一些这种类型的模拟对象数组"TypeA[]"。

我正在尝试执行此操作,但遇到了 classcastexception:

List mockList = Mockito.anyListOf(TypeA.class);

when(someService.create(Mockito.any(TypeB.class), (TypeA[])mockList.toArray())).thenReturn(1);

报错信息告诉你的很清楚:

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"))

Mockito.anyListOf返回对象的方法调用只能在stubbing或verification中。

你可以简单地模拟数组:

when(mockTest.create(any(TypeB.class), any(TypeA[].class))).thenReturn(1);