4 package org.wamblee.test;
6 import static org.mockito.Mockito.*;
8 import java.lang.reflect.InvocationHandler;
9 import java.lang.reflect.InvocationTargetException;
10 import java.lang.reflect.Method;
11 import java.lang.reflect.Proxy;
13 import net.sf.cglib.proxy.Enhancer;
14 import net.sf.cglib.proxy.MethodInterceptor;
15 import net.sf.cglib.proxy.MethodProxy;
18 * Resettable mock is a utility to support reset functionality for mockito.
20 * @author Erik Brakkee
24 public class ResettableMock<T> {
26 private static class MockitoInvocationHandler<T> implements
29 private Class<T> _class;
32 public MockitoInvocationHandler(Class<T> aClass) {
46 public Object intercept(Object aProxy, Method aInterceptedMethod,
47 Object[] aArgs, MethodProxy aMethodProxy) throws Throwable {
49 return aInterceptedMethod.invoke(_mock, aArgs);
50 } catch (InvocationTargetException e) {
57 * Invocation handler that delegates to the current mockito mock and allows
58 * creation of a new mock.
60 private ResettableMock.MockitoInvocationHandler<T> _handler;
63 * Proxy object to be passed to tested classes.
68 * Constructs the resettable mock.
71 * Type to mock. Must be an interface or a non-final class with a
72 * default constructor.
74 public ResettableMock(Class<T> aType) {
75 if (!aType.isInterface()) {
76 throw new IllegalArgumentException("Class '" + aType.getName()
77 + "' must be an interface");
79 _handler = new MockitoInvocationHandler(aType);
80 Enhancer enhancer = new Enhancer();
81 enhancer.setSuperclass(aType);
82 enhancer.setCallback(_handler);
83 _proxy = (T) enhancer.create();
87 * Resets the mock effectively forgetting all previous interactions and
95 * Gets the current mock object to pass to mockito calls.
97 * @return Mock object.
100 return _handler.getMock();
104 * Returns the proxy that your tested classes will used.
106 * @return Proxy object.
108 public T getProxy() {