user1428716 user1428716 - 3 years ago 167
Java Question

How to pass parameters to a mock object

I have a class

class SearchCriteria
someEnum with values like "A","B"
int id;

I want to mock a Delgeate with one method as

class Delegate
int getSomeStuff(SearchCriteria search)
//call dao and return count

How do I pass SearchCriteria using Mock

Delegate mock;

Here for different Use cases of SearchCriteria , I want different values to be returned

So if enum in SearchCriteria is set to A thenReturn 0 and in B then return 1 ...etc

How do I achieve this ?

Answer Source

You can do this:


An alternative is to provide a method to be executed when your mock is invoked upon, using this construct:

   when(mock.getSomeStuff(any(Criteria.class))).thenAnswer(new Answer<Integer>{
        public Integer answer(InvocationOnMock invocation) throws Throwable {
           // inspect args in invocation and return
           // ...

which allows you to perform more complex responses.

and inspect upon the arguments provided.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download