VerboseMockInvocationLogger.java revision e0ae5d7e87b1dd6e789803c1b9615a84bd7488b7
1/* 2 * Copyright (c) 2007 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5 6package org.mockito.internal.debugging; 7 8import org.mockito.invocation.DescribedInvocation; 9import org.mockito.listeners.InvocationListener; 10import org.mockito.listeners.MethodInvocationReport; 11 12import java.io.PrintStream; 13 14/** 15 * Logs all invocations to standard output. 16 * 17 * Used for debugging interactions with a mock. 18 */ 19public class VerboseMockInvocationLogger implements InvocationListener { 20 21 // visible for testing 22 final PrintStream printStream; 23 24 private int mockInvocationsCounter = 0; 25 26 public VerboseMockInvocationLogger() { 27 this(System.out); 28 } 29 30 public VerboseMockInvocationLogger(PrintStream printStream) { 31 this.printStream = printStream; 32 } 33 34 public void reportInvocation(MethodInvocationReport methodInvocationReport) { 35 printHeader(); 36 printStubInfo(methodInvocationReport); 37 printInvocation(methodInvocationReport.getInvocation()); 38 printReturnedValueOrThrowable(methodInvocationReport); 39 printFooter(); 40 } 41 42 private void printReturnedValueOrThrowable(MethodInvocationReport methodInvocationReport) { 43 if (methodInvocationReport.threwException()) { 44 String message = methodInvocationReport.getThrowable().getMessage() == null ? "" : " with message " + methodInvocationReport.getThrowable().getMessage(); 45 printlnIndented("has thrown: " + methodInvocationReport.getThrowable().getClass() + message); 46 } else { 47 String type = (methodInvocationReport.getReturnedValue() == null) ? "" : " (" + methodInvocationReport.getReturnedValue().getClass().getName() + ")"; 48 printlnIndented("has returned: \"" + methodInvocationReport.getReturnedValue() + "\"" + type); 49 } 50 } 51 52 private void printStubInfo(MethodInvocationReport methodInvocationReport) { 53 if (methodInvocationReport.getLocationOfStubbing() != null) { 54 printlnIndented("stubbed: " + methodInvocationReport.getLocationOfStubbing()); 55 } 56 } 57 58 private void printHeader() { 59 mockInvocationsCounter++; 60 printStream.println("############ Logging method invocation #" + mockInvocationsCounter + " on mock/spy ########"); 61 } 62 63 private void printInvocation(DescribedInvocation invocation) { 64 printStream.println(invocation.toString()); 65// printStream.println("Handling method call on a mock/spy."); 66 printlnIndented("invoked: " + invocation.getLocation().toString()); 67 } 68 69 private void printFooter() { 70 printStream.println(""); 71 } 72 73 private void printlnIndented(String message) { 74 printStream.println(" " + message); 75 } 76 77} 78