Photo by Eve Maier on Unsplash

The Argument Is the (Mockito) Answer

Make a Method Return Values Based on Its Input Arguments

Kenneth Kousen
7 min readMay 10, 2023

--

In this article:
* The Service I Want to Test
* Testing Approaches
* Setting Expectations
* Is There a Better Way?
* Simplifying the Test
* A More Elegant Solution
* Summing Up

For developers who prefer to watch a video rather than read a blog post, here a video covering this topic:

If, on the other hand, you prefer to read text, please continue. Of course, ideally you’ll enjoy doing both. :)

The Service I Want to Test

I am trying to test a service that saves a list of Person objects. In my case, the PersonService class has a method called savePeople that takes a vararg list of persons and saves them one by one:

public class PersonService {
private final PersonRepository repository;

public PersonService(PersonRepository repository) {
this.repository = repository;
}

public List<Integer> savePeople(Person... person) {
return Arrays.stream(person)…

--

--

Kenneth Kousen
The Pragmatic Programmers

Author of the books Mockito Made Clear, Help Your Boss Help You, Kotlin Cookbook, Modern Java Recipes, Gradle Recipes for Android, and Making Java Groovy