如何使用通用参数类型模拟方法

时间:2018-08-06 10:35:33

标签: java junit mockito

我有这种方法

public <T, R> R deepCopy(T source, R destination) {
   beanMapper.map(source, destination);
   return destination;
}

并希望使用类似的方法参数进行模拟

mock.deepCopy(classA(), classB()).thenReturn(classB());
mock.deepCopy(classB(), classC()).thenReturn(classC());

但收到类强制转换异常。

1 个答案:

答案 0 :(得分:1)

关于

doAnswer(invocation -> {
       Object arg1 = invocation.getArguments()[0];
       Object arg2 = invocation.getArguments()[1];

       if(arg1 instanceof Integer && arg2 instanceof String)
           return "something";
        if(arg1 instanceof String && arg2 instanceof Boolean)
            return false;

        return false;
}).when(yourmock).deepCopy(any(), any());

现在,如果您传递带有参数(1,“ abcd”)的方法,则模拟将返回“ something”。如果您通过(“ abcd”,true),则返回false

相关问题