Skip to content

Instantly share code, notes, and snippets.

@kpunith8
Forked from dimosr/MockitoBehaviour.java
Created April 25, 2019 05:55
Show Gist options
  • Save kpunith8/0b10e82ec7839ace78f52e2bb645a268 to your computer and use it in GitHub Desktop.
Save kpunith8/0b10e82ec7839ace78f52e2bb645a268 to your computer and use it in GitHub Desktop.
Mockito when/thenReturn & doReturn/when patterns behaviour
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Map;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
@Mock
Map<String, Integer> map;
/** (Succeeds)
* Map will always return:
* - 1, when queried with "first"
* - 2, when queried with "second"
*/
@Test
public void testChainedWhenWithDifferentParams() {
when(map.get("first"))
.thenReturn(1);
when(map.get("second"))
.thenReturn(2);
Assert.assertEquals(Integer.valueOf(1), map.get("first"));
Assert.assertEquals(Integer.valueOf(2), map.get("second"));
}
/** (Fails)
* Map will always return:
* - 2, when asked with first
*
* The second command overrides the first expectation
*/
@Test
public void testChainedWhenWithSameParam() {
when(map.get("first"))
.thenReturn(1);
when(map.get("first"))
.thenReturn(2);
Assert.assertEquals(Integer.valueOf(1), map.get("first"));
Assert.assertEquals(Integer.valueOf(2), map.get("first"));
}
/** (Succeeds)
* Map will return:
* - 1, at the first time it's invoked with "first"
* - 2, all the subsequent times when invoked with "first"
*/
@Test
public void testChainedThenReturnWithSameParam() {
when(map.get("first"))
.thenReturn(1)
.thenReturn(2);
Assert.assertEquals(Integer.valueOf(1), map.get("first"));
Assert.assertEquals(Integer.valueOf(2), map.get("first"));
}
/** (Succeeds)
* Map will always return:
* - 1, when invoked with "first"
* - 2, when invoked with "second"
*/
@Test
public void testChainedDoReturnWithDifferentParams() {
doReturn(1)
.when(map).get("first");
doReturn(2)
.when(map).get("second");
Assert.assertEquals(Integer.valueOf(1), map.get("first"));
Assert.assertEquals(Integer.valueOf(2), map.get("second"));
}
/** (Fails)
* Map will always return:
* - 2, when asked with first
*
* The second command overrides the first expectation
*/
@Test
public void testChainedDoReturnWithSameParam() {
doReturn(1)
.when(map).get("first");
doReturn(2)
.when(map).get("first");
Assert.assertEquals(Integer.valueOf(1), map.get("first"));
Assert.assertEquals(Integer.valueOf(2), map.get("first"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment