0

Is there a way to distinguish between generic classes in mockito for mappings?

The method call is as follow (except different logic than returning true.:

userWrapper.wrapCall( new Client<Boolean, User>(){
   @override 
   public Boolean run(){
         return true
   }
 }

For example

    Client<Boolean, User> c1 = Mockito.any();
    Client<Account, User> c2 = Mockito.any();

    when (userWrapper.wrapCall( c1 )).thenReturn( true );
    when (userWrapper.wrapCall( c2 )).thenReturn( new Account() );

However this fails, as it seems that it just Maps callableclient as opposed to taking into account the Generics. I tried using returnAnswer however, the .getArgs only returns the userwrapper, not the c1/c2 passed into the method.

Nyxter
  • 365
  • 3
  • 18

1 Answers1

0

First, remember that generics work via erasure. This means that almost nothing will allow Mockito to distinguish between c1 and c2 the way you have it here.

Second, never extract Mockito matchers like any to variables. Mockito matchers work via side effects, so calls like the one above are likely to break in weird ways. Extracting static methods to keep the call order correct, though, should work fine.

Your two best bets are to either distinguish one map from another based on its contents, such as this one using a Hamcrest map matcher:

// Will likely need casts or explicit method type arguments.
when(userWrapper.wrapCall(argThat(hasKey(isInstanceOf(Boolean.class)))))
    .thenReturn(true);
when(userWrapper.wrapCall(argThat(hasKey(isInstanceOf(Account.class)))))
    .thenReturn(new Account());

...or to examine the call order, which can lead to brittle tests:

// May also need generics specified, subject to your Client class definition.
when(userWrapper.wrapCall(Matchers.any()))
    .thenReturn(true).thenReturn(new Account());

That latter one may be better expressed using doReturn syntax, which cannot check its return type(s).

Community
  • 1
  • 1
Jeff Bowman
  • 74,544
  • 12
  • 183
  • 213
  • Thanks the second works, but means its brittle so has to go constantly in, I couldn't seemt o get the first one to work. – Nyxter Oct 15 '14 at 09:00