0

有没有办法区分 mockito 中用于映射的泛型类?

方法调用如下(除了返回true不同的逻辑。:

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

例如

    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() );

然而这失败了,因为它似乎只是 Maps callableclient 而不是考虑泛型。我尝试使用 returnAnswer 但是,.getArgs 只返回用户包装器,而不是传递给方法的 c1/c2。

4

1 回答 1

0

首先,请记住泛型通过擦除工作。这意味着几乎没有任何东西可以让 Mockito 区分你在这里拥有它的方式c1c2

其次,永远不要像variables一样提取 Mockito 匹配器anyMockito 匹配器通过副作用工作,因此像上面这样的调用可能会以奇怪的方式中断。但是,提取静态方法以保持调用顺序正确应该可以正常工作。

您最好的两个选择是根据其内容将一张地图与另一张地图区分开来,例如使用Hamcrest 地图匹配器的这张地图:

// 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());

...或检查调用顺序,这可能导致脆弱的测试:

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

后一种可能使用doReturn无法检查其返回类型的语法更好地表达。

于 2014-10-15T03:28:45.090 回答