Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

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

1 Answer

0 votes
by (46k points)
edited by

when(

fooDao.getBar(

any(Bazoo.class)

)

).thenReturn(myFoo);

Are you interested in learning Java from the basics! Refer to this video on Java provided by Intellipaat:

instead (to withdraw nulls):

when(

fooDao.getBar(

(Bazoo)notNull()

)

).thenReturn(myFoo);

Don't neglect to carry equals (several others are possible):

For Mockito 2.1.0 and later:

import static org.mockito.ArgumentMatchers.*;

For more traditional versions:

import static org.mockito.Matchers.*;

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Sep 30, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

Browse Categories

...