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.
A stub is a fake class that comes with preprogrammed return values. It's injected into the class under test to give you absolute control over what's being tested as input. A typical stub is a database connection that allows you to mimic any scenario without having a real database.
Mockito Verify methods are used to check that certain behavior happened. We can use Mockito verify methods at the end of the testing method code to make sure that specified methods are called.
For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.
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.*;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With