Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Mockito stub a method without regard to the argument?

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.

like image 943
Eric Wilson Avatar asked May 11 '11 19:05

Eric Wilson


People also ask

What does stub do in Mockito?

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.

Does Mockito verify call the method?

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.

Can Mockito test private methods?

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.


1 Answers

when(   fooDao.getBar(     any(Bazoo.class)   ) ).thenReturn(myFoo); 

or (to avoid nulls):

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.*; 
like image 161
Tomasz Nurkiewicz Avatar answered Sep 20 '22 03:09

Tomasz Nurkiewicz