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(?);
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.
@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.
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.
Use the @Mock
annotation in your test since Mockito can use type reflection:
@Mock
private ArrayList<User> mockArrayList;
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