对采用类< T>的方法进行存根作为参数与Mockito
有一个通用的方法,接受一个类作为参数,我有问题,它与Mockito stubbing。方法如下:
There is a generic method that takes a class as parameter and I have problems stubbing it with Mockito. The method looks like this:
public <U extends Enum<U> & Error, T extends ServiceResponse<U>> T validate(
Object target, Validator validator, Class<T> responseClass,
Class<U> errorEnum);
这是上帝可怕,至少对我...我可以想象生活没有它,的代码库很高兴地使用它...
It's god awful, at least to me... I could imagine living without it, but the rest of the code base happily uses it...
我将在我的单元测试中,stub这个方法返回一个新的空对象。但是我怎么做这个与mockito?我试过:
I was going to, in my unit test, stub this method to return a new empty object. But how do I do this with mockito? I tried:
when(serviceValidatorStub.validate(
any(),
isA(UserCommentRequestValidator.class),
UserCommentResponse.class,
UserCommentError.class)
).thenReturn(new UserCommentResponse());
但是由于我混合和匹配匹配器和原始值,我得到org.mockito.exceptions。
but since I am mixing and matching matchers and raw values, I get "org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers!"
问题是,你不能混合参数匹配器和真正的参数在嘲笑的电话。所以,而是这样做:
The problem is, you cannot mix argument matchers and real arguments in a mocked call. So, rather do this:
when(serviceValidatorStub.validate(
any(),
isA(UserCommentRequestValidator.class),
eq(UserCommentResponse.class),
eq(UserCommentError.class))
).thenReturn(new UserCommentResponse());
注意使用 eq()
请参阅: http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#3
此外,您可以使用
参数匹配器
类<?>
types - 这匹配相同的标识,如 ==
Java运算符。
Also, you could use the same()
argument matcher for Class<?>
types - this matches same identity, like the ==
Java operator.