Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock an array containing objects using mockito?

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?

like image 532
Klyner Avatar asked May 21 '26 11:05

Klyner


1 Answers

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!

like image 131
GhostCat Avatar answered May 23 '26 05:05

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!