When I’m writing unit tests with Mockito, I’ll often find that I call a getter on one of my injected mocks, and then call a method off the returned object.
So far, I’ve done that something like this:
@Mock
private Randomizer r;
@Mock
private Random random;
@InjectMocks
private NodeGenerator ng = new NodeGenerator();
@Test
public void nodeIsDuplicate() {
when(r.getRandom()).thenReturn(random);
when(random.nextInt(2)).thenReturn(1);
[...]
}
But it seems like such a waste to have to mock out the random and set up a second when for it. Is there some way to make my when statement more like:
when(r.getRandom().nextInt(2)).thenReturn(1);
Without having to mock out the random, so I can do it all on one line with just my Randomizer mock?
You want Mockito’s One liner stubs.
Edit:
Upon closer inspection that may not be exactly what you are looking for, but it can reduce some of that boiler plate code for you.
Wat you are looking for is, indeed as the comment suggests, deep stubs.
For your example it would be :