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);
Mocking is usually accomplished by introducing a dynamic proxy on an interface or a subclass of a class. Since a date array is a final class, it is neither an interface nor subclassable, so that takes away the normal approaches for creating a mock.
We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object. We are using JUnit 5 to write test cases in conjunction with Mockito to mock objects.
When you create a mock, you create an associated behavior object that controls mock behavior. Use this object to define mock method and property behavior (stub). For more information on creating a mock, see Create Mock Object.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With