1 /* 2 * Copyright (c) 2007 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5 package org.mockito.internal.handler; 6 7 import org.mockito.invocation.InvocationContainer; 8 import org.mockito.invocation.Invocation; 9 import org.mockito.invocation.MockHandler; 10 import org.mockito.listeners.InvocationListener; 11 import org.mockito.mock.MockCreationSettings; 12 13 import java.util.List; 14 15 import static org.mockito.internal.exceptions.Reporter.invocationListenerThrewException; 16 17 /** 18 * Handler, that call all listeners wanted for this mock, before delegating it 19 * to the parameterized handler. 20 * 21 * Also imposterize MockHandlerImpl, delegate all call of InternalMockHandler to the real mockHandler 22 */ 23 class InvocationNotifierHandler<T> implements MockHandler<T> { 24 25 private final List<InvocationListener> invocationListeners; 26 private final MockHandler<T> mockHandler; 27 InvocationNotifierHandler(MockHandler<T> mockHandler, MockCreationSettings<T> settings)28 public InvocationNotifierHandler(MockHandler<T> mockHandler, MockCreationSettings<T> settings) { 29 this.mockHandler = mockHandler; 30 this.invocationListeners = settings.getInvocationListeners(); 31 } 32 handle(Invocation invocation)33 public Object handle(Invocation invocation) throws Throwable { 34 try { 35 Object returnedValue = mockHandler.handle(invocation); 36 notifyMethodCall(invocation, returnedValue); 37 return returnedValue; 38 } catch (Throwable t){ 39 notifyMethodCallException(invocation, t); 40 throw t; 41 } 42 } 43 44 notifyMethodCall(Invocation invocation, Object returnValue)45 private void notifyMethodCall(Invocation invocation, Object returnValue) { 46 for (InvocationListener listener : invocationListeners) { 47 try { 48 listener.reportInvocation(new NotifiedMethodInvocationReport(invocation, returnValue)); 49 } catch(Throwable listenerThrowable) { 50 throw invocationListenerThrewException(listener, listenerThrowable); 51 } 52 } 53 } 54 notifyMethodCallException(Invocation invocation, Throwable exception)55 private void notifyMethodCallException(Invocation invocation, Throwable exception) { 56 for (InvocationListener listener : invocationListeners) { 57 try { 58 listener.reportInvocation(new NotifiedMethodInvocationReport(invocation, exception)); 59 } catch(Throwable listenerThrowable) { 60 throw invocationListenerThrewException(listener, listenerThrowable); 61 } 62 } 63 } 64 getMockSettings()65 public MockCreationSettings<T> getMockSettings() { 66 return mockHandler.getMockSettings(); 67 } 68 getInvocationContainer()69 public InvocationContainer getInvocationContainer() { 70 return mockHandler.getInvocationContainer(); 71 } 72 73 } 74