Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 808
iPhoneJavaDev Avatar asked Jan 28 '15 03:01

iPhoneJavaDev


People also ask

How do you mock an array of objects?

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.

How to mock any object of a class?

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.

How can specify mock behavior of an object?

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.


1 Answers

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);
like image 169
Dongqing Avatar answered Oct 04 '22 03:10

Dongqing