I'm trying to test some legacy code, using Mockito.
I want to stub a FooDao
that is used in production as follows:
foo = fooDao.getBar(new Bazoo());
I can write:
when(fooDao.getBar(new Bazoo())).thenReturn(myFoo);
But the obvious problem is that getBar()
is never called with the same Bazoo
object that I stubbed the method for. (Curse that new
operator!)
I would love it if I could stub the method in a way that it returns myFoo
regardless of the argument. Failing that, I'll listen to other workaround suggestions, but I'd really like to avoid changing the production code until there is reasonable test coverage.
when(
fooDao.getBar(
any(Bazoo.class)
)
).thenReturn(myFoo);
or (to avoid null
s):
when(
fooDao.getBar(
(Bazoo)notNull()
)
).thenReturn(myFoo);
Don't forget to import matchers (many others are available):
For Mockito 2.1.0 and newer:
import static org.mockito.ArgumentMatchers.*;
For older versions:
import static org.mockito.Matchers.*;