X-Git-Url: http://wamblee.org/gitweb/?a=blobdiff_plain;f=support%2Fgeneral%2Fsrc%2Ftest%2Fjava%2Forg%2Fwamblee%2Ftest%2FResettableMock.java;fp=support%2Fgeneral%2Fsrc%2Ftest%2Fjava%2Forg%2Fwamblee%2Ftest%2FResettableMock.java;h=47cc67474774cc53ebf940822d765ab80595d047;hb=8557fbe8c7ea4e1cbcbf10d3c4e8c60c9c1e312b;hp=0000000000000000000000000000000000000000;hpb=34b0dc0bca5a2d99394b9692b4ea14ce9e2141b7;p=utils diff --git a/support/general/src/test/java/org/wamblee/test/ResettableMock.java b/support/general/src/test/java/org/wamblee/test/ResettableMock.java new file mode 100644 index 00000000..47cc6747 --- /dev/null +++ b/support/general/src/test/java/org/wamblee/test/ResettableMock.java @@ -0,0 +1,95 @@ +/** + * + */ +package org.wamblee.test; + +import static org.mockito.Mockito.*; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +/** + * Resettable mock is a utility to support reset functionality for mockito. + * @author Erik Brakkee + * + * @param + */ +public class ResettableMock { + + private static class MockitoInvocationHandler implements + InvocationHandler { + + private Class _class; + private T _mock; + + public MockitoInvocationHandler(Class aClass) { + _class = aClass; + _mock = mock(aClass); + } + + public void reset() { + _mock = mock(_class); + } + + public T getMock() { + return _mock; + } + + @Override + public Object invoke(Object aProxy, Method aMethod, Object[] aArgs) + throws Throwable { + return aMethod.invoke(_mock, aArgs); + } + } + + /** + * Invocation handler that delegates to the current mockito mock and allows + * creation of a new mock. + */ + private ResettableMock.MockitoInvocationHandler _handler; + + /** + * Proxy object to be passed to tested classes. + */ + private T _proxy; + + /** + * Constructs the resettable mock. + * @param aType Type to mock. Must be an interface type. + */ + public ResettableMock(Class aType) { + if ( !aType.isInterface()) { + throw new IllegalArgumentException("Class '" + aType.getName() + "' must be an interface"); + } + _handler = new MockitoInvocationHandler(aType); + _proxy = (T) Proxy.newProxyInstance(aType.getClassLoader(), + new Class[] { aType }, _handler); + } + + /** + * Resets the mock effectively forgetting all previous interactions and verifications. + */ + public void reset() { + _handler.reset(); + } + + /** + * Gets the current mock object to pass to mockito calls. + * + * @return Mock object. + */ + public T getMock() { + return _handler.getMock(); + } + + /** + * Returns the proxy that your tested classes will used. + * + * @return Proxy object. + */ + public T getProxy() { + return _proxy; + } + +} \ No newline at end of file