Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a mock of list of a custom data type in Mockito?

I have a class User with the following definition :

class User {

  Integer id;
  String name;
  String addr;

  //getters and setters

}

Now while testing a function, I am required to return a list of mocked Users for a stub, something like:

Mockito.when(userService.getListOfUsers()).thenReturn(mockList);

Now this mockList could be created as the following :

List mockList = Mockito.mock(ArrayList.class);

But this mockList could be a list of anything. I won't be able to ensure its type. Is there a way to create list of :

List<User> mockListForUser = Mockito.mock(?);
like image 276
Sourabh Avatar asked Jun 17 '14 07:06

Sourabh


People also ask

How do you make a mock in Mockito?

Mock will be created by Mockito. Here we've added two mock method calls, add() and subtract(), to the mock object via when(). However during testing, we've called subtract() before calling add(). When we create a mock object using create(), the order of execution of the method does not matter.

What is difference between @mock and @injectmock?

@Mock is used to create mocks that are needed to support the testing of the class to be tested. @InjectMocks is used to create class instances that need to be tested in the test class. Annotated class to be tested dependencies with @Mock annotation.


2 Answers

You probably want to populate a normal list with your mocked objects. E.g.

List<User> mockList = new ArrayList<>();

User mockUser1 = Mockito.mock(User.class);
// ...    

mockList.add(mockUser1);
// etc.

Note that by default, Mockito returns an empty collection for any mocked methods that returns a collection. So if you just want to return an empty list, Mockito will already do that for you.

like image 149
Duncan Jones Avatar answered Oct 04 '22 18:10

Duncan Jones


Use the @Mock annotation in your test since Mockito can use type reflection:

@Mock
private ArrayList<User> mockArrayList;
like image 21
Jean Logeart Avatar answered Oct 04 '22 18:10

Jean Logeart