3

In my Mockito unit test I am trying to mock an array containing instances of the object Message. To do this I try to mock it like normal objects so like:

private var messagesMock = mock(Array<Message>::class.java)

This gives the following error/exception:

org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class [Lrobot.fsrt.robotguest.common.data.Message;
Mockito cannot mock/spy because :
 - VM does not not support modification of given type

How to mock an array the right way using Mockito?

1
  • Also note: your question isn't really clear. Is Message a variable, or is it a generic type. Do you want to have ONE array with the object Message within it, or do you want to create some generic Array<Message> instance? So a real minimal reproducible example with additional context would definitely help here. Commented May 20, 2019 at 6:42

1 Answer 1

3

A distinct non-answer: you (almost) never mock objects that represent containers!

An array is just that: a container.

You create the container with the size you need, and then you put your mocked objects into that ordinary container, and make sure that container with your prepared content gets used by your production code.

It is as simple as that: you don't mock arrays, or lists, or maps: you create them as is, and manipulate their content!

Sign up to request clarification or add additional context in comments.

2 Comments

What if I want to test the iterator?
What do you mean? Testing your own implementation of some interface like iterable is a different story.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.