问题描述
有一个将类作为参数的通用方法,我在使用 Mockito 存根时遇到问题.该方法如下所示:
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...
我打算在我的单元测试中存根这个方法以返回一个新的空对象.但是我如何用 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.misusing.InvalidUseOfMatchersException:参数匹配器的无效使用!"
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()
参数匹配器来匹配相等性.
Notice the use of the eq()
argument matcher for matching equality.
参见:https://static.javadoc.io/org.mockito/mockito-core/1.10.19/org/mockito/Matchers.html#eq(T)
此外,您可以将 same()
参数匹配器用于 Class<?>
类型 - 这匹配相同的身份,例如 ==代码> Java 运算符.
Also, you could use the same()
argument matcher for Class<?>
types - this matches same identity, like the ==
Java operator.
这篇关于存根采用 Class<T> 的方法作为 Mockito 的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!