verify(channel).subscribe(any(Callback.class), eq(100), eq(true))
I was toying with some code the other day and it occurred to me that I should be able to write my own
any
method that achieves what I'm looking for without requiring my other arguments to be matchers. The code below is what I've started using as an alternative.
public staticT any(final Class clazz) {
MethodInterceptor advice = new MethodInterceptor() {
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
if (method.getName().equals("equals")) {
return clazz.isInstance(obj);
}
return null;
}
};
return new ProxyCreator().imposterise(advice, clazz);
}
Using my any implementation the first example code can be written like the example below.
verify(channel).subscribe(any(Callback.class), 100, true)
My implementation relies on classes from cglib and spruice; however, you could copy the necessary class from spruice very easily. Here are the referenced classes:
- net.sf.cglib.proxy.MethodInterceptor
- net.sf.cglib.proxy.MethodProxy
- org.spruice.proxy.ProxyCreator
A very elegant solution, thanks for sharing :-)
ReplyDeleteWe had run into similar problems with the matchers.
Wow. Interesting idea! I'd like to incorporate it into Mockito somehow. For some classes you would still need to use good old any() and eq() (e.g. final classes, classes with final equals() :-D )
ReplyDeleteSzczepan, Please feel free to add the idea to Mockito. I'm glad you like it. =)
ReplyDeleteCheers, Jay
Hey Jay , for the 'T' modifier
ReplyDeletei'm getting the following import
import org.apache.poi.hssf.record.formula.functions.T;
is this correct?
Ashwyn, T is just a generic type. It's not something you should need to import.
ReplyDeleteCheers, Jay
Just use Mockito.eq(T)
ReplyDelete