Monday, June 08, 2009
Mockito non-hamcrest any matcher
These days I'm using Mockito for my behavior based tests. I like Mockito's integration with Hamcrest, but I don't always like the viral matcher requirement. In particular, if I have a method that takes 3 arguments, I don't like the fact that if I use a matcher for one argument I have to use a matcher for all 3. For example, in the following verification I don't care about the callback instance, but I do care about the timeout and the async flag.
I was toying with some code the other day and it occurred to me that I should be able to write my own
The code below is what I've started using as an alternative.
Using my any implementation the first example code can be written like the example below.
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:
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
Labels: mockito
Comments:
<< Home
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 )
Hey Jay , for the 'T' modifier
i'm getting the following import
import org.apache.poi.hssf.record.formula.functions.T;
is this correct?
Post a Comment
i'm getting the following import
import org.apache.poi.hssf.record.formula.functions.T;
is this correct?
<< Home




