0

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; 
when(mock.getSomeStuff(??))thenReturn(5); 

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 ?

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
user1428716
  • 2,078
  • 2
  • 18
  • 37

2 Answers2

3

You can do this:

when(mock.getSomeStuff(CriteriaA)).thenReturn(0);   
when(mock.getSomeStuff(CriteriaB)).thenReturn(1);

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>{
        @Override
        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.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • getSomeStuff expects an Object ..which may be comprised of Enum(s) and may be other Primitive / Class .. how it will work in the scenario when multiple combination has to be fed – user1428716 Jun 04 '14 at 08:59
  • Note my second solution, which allows you to inspect the criteria and return a suitable result – Brian Agnew Jun 04 '14 at 09:00
0

If you need to inspect the parameter, then you can just can use a fake implementation, like:

Delegate mock = new Delegate() {
    public int getSomeStuff(SearchCriteria search) {
        // Check search param
        return 0;
    }
};
fgb
  • 18,439
  • 2
  • 38
  • 52