您可以通过实现一个新的 Matcher 来做到这一点,该 Matcher 在调用 match 时捕获参数。这可以稍后检索。
class CapturingMatcher<T> extends BaseMatcher<T> {
private final Matcher<T> baseMatcher;
private Object capturedArg;
public CapturingMatcher(Matcher<T> baseMatcher){
this.baseMatcher = baseMatcher;
}
public Object getCapturedArgument(){
return capturedArg;
}
public boolean matches(Object arg){
capturedArg = arg;
return baseMatcher.matches(arg);
}
public void describeTo(Description arg){
baseMatcher.describeTo(arg);
}
}
然后,您可以在设置期望时使用它。
final CapturingMatcher<ComplexObject> captureMatcher
= new CapturingMatcher<ComplexObject>(Expectations.any(ComplexObject.class));
mockery.checking(new Expectations() {{
one(complexObjectUser).registerComplexity(with(captureMatcher));
}});
service.setComplexUser(complexObjectUser);
ComplexObject co =
(ComplexObject)captureMatcher.getCapturedArgument();
co.goGo();