For mocking, you're trying to simulate an object implementation, and the when
call helps you describe the return values that the simulated object should have. Because the documentation is pretty self-explanatory, I'll assume for the rest of the answer that you're looking for how Mockito is supposed to work and how when
helps you set up your mocks.
Let's make an interface to work with:
interface Foo {
int bar();
}
Presumably there is some implementor of Foo.bar
out there, but maybe that implementation is hard to use in tests: It may use file storage, a network service, or some sort of random value. (Or, maybe, you haven't written the real implementation yet.) Now, you've written a class called YourClass
that depends on a Foo
instance, but you can't use a real one in your tests for any of the above reasons. What do you do?
One way is to write a very small implementation in your test:
Foo fakeFoo = new Foo() {
@Override public int bar() { return 42; }
};
YourClass yourClass = new YourClass(fakeFoo);
Now you've written fakeFoo
to have a predictable and easy-to-understand return value. This works for something this small, but it doesn't scale: What if Foo has a dozen methods? What if rather than returning 42 every time, you want to return a different predictable value each time? What if you want to check later on whether bar
was called? Mockito helps you do all that by switching the syntax:
Foo mockFoo = Mockito.mock(Foo.class);
when(mockFoo.bar()).thenReturn(42); // <- the statement you're asking about
YourClass yourClass = new YourClass(mockFoo);
Now, using the when
statement, you're telling the mock Foo you've created what to return, which is just like the fake Foo implementation you wrote above for the same reasons. From there, you can write more when
statements, or give your thenReturn
more values to return in sequence, or use verify
to check whether calls have been made. Above all, remember: You're not using when
or making a mock of the class you're testing; you're mocking the classes that collaborate with the class you're testing.