The long way through Software Craftsmanship

Multiple return values in a Mockito Stub

Aug 7, 2015 - 1 minute read - Comments - mockitotipstubjava

I’ve been asked today how to return multiple return values from a Mockito Spy, effectively using the spy as a Stub, as well.

package com.example.spike;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.mockito.Spy;

public class DifferentReturnValues {

	@Spy
	private Spike1 spike1 = new Spike1();


	@Test
	public void spike1() {
		spike1 = spy(spike1);
		when(spike1.getBool()).thenReturn(false, true);

		assertThat(spike1.getBool(), is(false));
		assertThat(spike1.getBool(), is(true));

		assertThat(spike1.getBool(), is(true));
		assertThat(spike1.getBool(), is(true));
	}


	private class Spike1 {
		public boolean getBool() {
			return true;
		}
	}
}

The key line is:

when(spike1.getBool()).thenReturn(false, true);

this makes the stubbed function to return multiple values:

assertThat(spike1.getBool(), is(false));
assertThat(spike1.getBool(), is(true));

The last value is repeated after the last defined value:

@Test
public void spike1() {
	spike1 = spy(spike1);
	when(spike1.getBool()).thenReturn(false, true);

	assertThat(spike1.getBool(), is(false));
	assertThat(spike1.getBool(), is(true));

	assertThat(spike1.getBool(), is(true));
	assertThat(spike1.getBool(), is(true));
}

If you want to loop over the values, you can implement it with the doAnswer method:

@Test
public void spike1() {
	spike1 = spy(spike1);
	when(spike1.getBool()).thenReturn(false, true);

	final boolean[] value = {true};

	doAnswer(invocation -> {
		value[0] = !value[0];
		return value[0];
	}).when(spike1).getBool();

	assertThat(spike1.getBool(), is(false));
	assertThat(spike1.getBool(), is(true));

	assertThat(spike1.getBool(), is(false));
	assertThat(spike1.getBool(), is(true));
}

Disclaimer about AI/GenAI

As of 2026-05-06, the text in these articles and blog entries has been written without AI/GenAI, except I sometimes use a spellchecker to fix errors. Think Word's spellchecker, not ChatGPT.

Notes, as of today (2026-05-06):

  • No code snippet has been automatically generated, nor vibe-coded, nor generated and reviewed.
  • I don’t have any article with AI contribution.

For future entries:

  • I may have used GenAI for the code in the repo. The code I exemplify/copy in the article will always be reviewed and tested, not vibe-coded. I will specify it in each snippet or at the top/bottom of the article.
  • I normally don't use it for the text contents, although if I have used it for the article text, it would be indicated as such.

Any entry before 2026-05-06 does not contain any AI/GenAI.

For more information, read the AI/GenAI Policy

Brown-bag session and Dojo: Beginning Clojure Recognizing dependencies