You could achieve this by creating MockMaker .
MockMaker is an extension point that allows you to use custom dynamic proxies and avoid using the default cglib / asm / objenesis implementation
Our custom implementation delegates all complex stuff to the default MockMaker : CglibMockMaker . It only decorates the createMock method by registering with the settings a InvocationListener parameter. This listener will be notified when an invocation been performed, allowing validateArguments and validateReturnValue to be used to call.
import org.mockito.internal.creation.CglibMockMaker; import org.mockito.invocation.Invocation; import org.mockito.invocation.MockHandler; import org.mockito.listeners.InvocationListener; import org.mockito.listeners.MethodInvocationReport; import org.mockito.mock.MockCreationSettings; import org.mockito.plugins.MockMaker; public class ValidationMockMaker implements MockMaker { private final MockMaker delegate = new CglibMockMaker(); public ValidationMockMaker() { } @Override public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) { settings.getInvocationListeners().add(new InvocationListener() { @Override public void reportInvocation(MethodInvocationReport methodInvocationReport) { Invocation invocation = (Invocation) methodInvocationReport.getInvocation(); validateArguments(invocation.getArguments()); validateReturnValue(methodInvocationReport.getReturnedValue()); } }); return delegate.createMock(settings, handler); } @Override public MockHandler getHandler(Object mock) { return delegate.getHandler(mock); } @Override public void resetMock(Object mock, MockHandler newHandler, MockCreationSettings settings) { delegate.resetMock(mock, newHandler, settings); } protected void validateArguments(Object... arguments) {
Last but not least, we need to tell Mockito to use our implementation. This can be done by adding a file.
mockito-extensions/org.mockito.plugins.MockMaker
containing our MockMaker class name:
ValidationMockMaker
See the Using the extension point section in javadoc.
source share