[Mockito] Mocking void methods to set a passed in parameter

Posted by {"name"=>"Palash Ray", "email"=>"paawak@gmail.com", "url"=>"https://www.linkedin.com/in/palash-ray/"} on January 14, 2014 · 1 min read

Consider the following badly designed code:
 

public interface BadPrecedentService {
    void setThePassedInList(List items);
}

This is being used as below:

public class BadPrecedentClient {
    private final BadPrecedentService badPrecedentService;
    public BadPrecedentClient(BadPrecedentService badPrecedentService) {
	this.badPrecedentService = badPrecedentService;
    }
    public List getNamesOfActiveItems() {
	List items = new ArrayList(10);
	badPrecedentService.setThePassedInList(items);
	List names = new ArrayList(items.size());
	for (Item item : items) {
	    if (item.isActive()) {
		names.add(item.getName());
	    }
	}
	return names;
    }
}

How can I test this method with Mockito? Look at the following snippet:

public class BadPrecedentClientTest {
    @Test
    public void testGetNamesOfActiveItems() {
	// given
	BadPrecedentService badPrecedentService = mock(BadPrecedentService.class);
	doAnswer(new Answer() {
	    public Object answer(InvocationOnMock invocation) {
		List items = (List) invocation.getArguments()[0];
		items.add(new Item("abc", true));
		items.add(new Item("def", false));
		items.add(new Item("ghi", true));
		items.add(new Item("jkl", false));
		items.add(new Item("xyz", true));
		return null;
	    }
	}).when(badPrecedentService).setThePassedInList(any(List.class));
	BadPrecedentClient testClass = new BadPrecedentClient(badPrecedentService);
	// when
	List result = testClass.getNamesOfActiveItems();
	// then
	assertEquals(Arrays.asList("abc", "ghi", "xyz"), result);
    }
}

The code can be found here: https://github.com/paawak/blog/tree/master/code/MockitoExample