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.exceptions.Reporter; 8 import org.mockito.internal.InternalMockHandler; 9 import org.mockito.internal.listeners.NotifiedMethodInvocationReport; 10 import org.mockito.internal.stubbing.InvocationContainer; 11 import org.mockito.invocation.Invocation; 12 import org.mockito.invocation.MockHandler; 13 import org.mockito.listeners.InvocationListener; 14 import org.mockito.mock.MockCreationSettings; 15 import org.mockito.stubbing.Answer; 16 import org.mockito.stubbing.VoidMethodStubbable; 17 18 import java.util.List; 19 20 /** 21 * Handler, that call all listeners wanted for this mock, before delegating it 22 * to the parameterized handler. 23 * 24 * Also imposterize MockHandlerImpl, delegate all call of InternalMockHandler to the real mockHandler 25 */ 26 class InvocationNotifierHandler<T> implements MockHandler, InternalMockHandler<T> { 27 28 private List<InvocationListener> invocationListeners; 29 private InternalMockHandler<T> mockHandler; 30 31 public InvocationNotifierHandler(InternalMockHandler<T> mockHandler, MockCreationSettings settings) { 32 this.mockHandler = mockHandler; 33 this.invocationListeners = settings.getInvocationListeners(); 34 } 35 36 public Object handle(Invocation invocation) throws Throwable { 37 try { 38 Object returnedValue = mockHandler.handle(invocation); 39 notifyMethodCall(invocation, returnedValue); 40 return returnedValue; 41 } catch (Throwable t){ 42 notifyMethodCallException(invocation, t); 43 throw t; 44 } 45 } 46 47 48 private void notifyMethodCall(Invocation invocation, Object returnValue) { 49 for (InvocationListener listener : invocationListeners) { 50 try { 51 listener.reportInvocation(new NotifiedMethodInvocationReport(invocation, returnValue)); 52 } catch(Throwable listenerThrowable) { 53 new Reporter().invocationListenerThrewException(listener, listenerThrowable); 54 } 55 } 56 } 57 58 private void notifyMethodCallException(Invocation invocation, Throwable exception) { 59 for (InvocationListener listener : invocationListeners) { 60 try { 61 listener.reportInvocation(new NotifiedMethodInvocationReport(invocation, exception)); 62 } catch(Throwable listenerThrowable) { 63 new Reporter().invocationListenerThrewException(listener, listenerThrowable); 64 } 65 } 66 } 67 68 public MockCreationSettings getMockSettings() { 69 return mockHandler.getMockSettings(); 70 } 71 72 public VoidMethodStubbable<T> voidMethodStubbable(T mock) { 73 return mockHandler.voidMethodStubbable(mock); 74 } 75 76 public void setAnswersForStubbing(List<Answer> answers) { 77 mockHandler.setAnswersForStubbing(answers); 78 } 79 80 public InvocationContainer getInvocationContainer() { 81 return mockHandler.getInvocationContainer(); 82 } 83 84 } 85