java - Mockito: How to match a String and List<String> arguments -


i'm trying verify whether correct parameters being invoked in method.

here's snippet of code i'm trying test:

criteria criteria = session.createcriteria(user.class); criteria.add(restrictions.in("type", arrays.aslist("employee", "supervisor"); 

verifying using:

mockito.verify(mocksession).createcriteria(user.class); mockito.verify(mockcriteria).add(restrictions.in("type", arrays.aslist("employee", "supervisor")); 

the first verify statement works. second doesn't because, believe, jvm detects 2 different list objects being compared to. however, when change second verify statement to:

mockito.verify(mockcriteria).add(restrictions.in("type", mockito.anylist()); 

it works charm. however, want ensure 2 strings, employee , supervisor, inside list , won't happen using mockito.anylist().

how work?

edit: please take note not wish verify whether list has been passed. want ensure correct strings passed inside list well

unfortunately, here cannot check want check matchers.

mockito matchers work via side-effects, call matcher tells mockito use matcher rather testing equality. means mockito matchers don't work @ when nested within objects criterion.

verify(mockcriteria).add(      restrictions.in("type", arrays.aslist("employee", "supervisor")); 

in above, don't use matchers, you're verifying mockcriteria.add called object equals criterion specify. however, if returned criterion doesn't override equals (and hashcode) test instances same—which never true here, because you're creating new 1 in verify statement.

verify(mockcriteria).add(restrictions.in("type", anylist())); 

here, looks like you're verifying mockcriteria.add called list, anylist() tells mockito skip checking 1 parameter , returns dummy value null. create criterion "type" in null, , mockito sees 1 any matcher on stack one-argument method call, discards newly-created invalid criterion, , checks add called @ all. looks everything's working, mockcriteria receive literally parameter including null , test still pass. (if using second matcher, or if add took 2 parameters, invaliduseofmatchersexception instead of false positive.)

to make work mockito matchers, need write own hamcrest matcher matches entire criterion, , use argthat let mockito match arguments it.


as andy turner mentioned, 1 way solve use argumentcaptor:

argumentcaptor<criterion> captor = argumentcaptor.forclass(criterion.class); verify(mockcriteria).add(captor.capture()); criterion criterion = captor.getvalue(); // assert against criterion 

however, warned may of limited use: criterion doesn't have lot of properties can inspect. may need use tostring(), in this question.


Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -