In this article, we will learn how to capture a list of a specific type with Mockito. We will present two approaches to creating an ArgumentCaptor object.
2. Test class
Let's start with our test class:
The ProcessingService is a simple service class that uses injected ListProcessor for processing a list of strings.
The ListProcessor service will iterate over each item in the list and add processed text at the end.
configure the ListProcessor to call a real method whenever we use processList(...),
next, we call ProcessingService.processList(...) method with test String as an argument,
in the next line: verify(listProcessor).processList(captor.capture()); - Mockito.verify(...) checks if this specific method was called. Additionally we added captor.capture() to check with what parameter this method was called,
captor.getValue() returns the object that was used as an argument to listProcessor.processList(...),
finally, we did some asserts to check if logic works as expected.
Note that we used hamcrest library to check if lists contains expected items:
4. Creating ArgumentCaptor object in the method body
We could also create an ArgumentCaptor inside the testing method:
This approach uses kind of java old-style semantics. IDE will warn you about the use of unchecked or unsafe operations. That's why we added @SuppressWarnings("unchecked") - to hide such warning.
5. Conclusion
In this article, we showed how to capture a list of a specific type using Mockito. We of course prefer a solution with @Captor annotation - it is clean and doesn't report any warning.
As usual, code introduced in this article is available in our GitHub repository.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}