iPhoneJavaDev
iPhoneJavaDev

Reputation: 825

Create Mockito Array of some Object type

I need to provide some mock object array of this type "TypeA[]".

I am trying to do this but getting classcastexception:

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

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

Upvotes: 5

Views: 32463

Answers (1)

Dongqing
Dongqing

Reputation: 686

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.anyListOf can only inside stubbing or verification .

you can simply do that to mock array :

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

Upvotes: 7

Related Questions