1 /* 2 * Copyright (c) 2016 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5 package org.mockito.internal.debugging; 6 7 import java.util.Collection; 8 import java.util.LinkedList; 9 10 import org.mockito.Mockito; 11 import org.mockito.internal.util.collections.ListUtil; 12 import org.mockito.invocation.Invocation; 13 import org.mockito.stubbing.Stubbing; 14 15 /** 16 * Prints invocations in human-readable, printable way 17 */ 18 public class InvocationsPrinter { 19 printInvocations(Object mock)20 public String printInvocations(Object mock) { 21 Collection<Invocation> invocations = Mockito.mockingDetails(mock).getInvocations(); 22 Collection<Stubbing> stubbings = Mockito.mockingDetails(mock).getStubbings(); 23 if (invocations.isEmpty() && stubbings.isEmpty()) { 24 return "No interactions and stubbings found for mock: " + mock; 25 } 26 27 StringBuilder sb = new StringBuilder(); 28 int x = 1; 29 for (Invocation i : invocations) { 30 if (x == 1) { 31 sb.append("[Mockito] Interactions of: ").append(mock).append("\n"); 32 } 33 sb.append(" ").append(x++).append(". ").append(i).append("\n"); 34 sb.append(" ").append(i.getLocation()).append("\n"); 35 if (i.stubInfo() != null) { 36 sb.append(" - stubbed ").append(i.stubInfo().stubbedAt()).append("\n"); 37 } 38 } 39 40 LinkedList<Stubbing> unused = 41 ListUtil.filter( 42 stubbings, 43 new ListUtil.Filter<Stubbing>() { 44 @Override 45 public boolean isOut(Stubbing s) { 46 return s.wasUsed(); 47 } 48 }); 49 50 if (unused.isEmpty()) { 51 return sb.toString(); 52 } 53 sb.append("[Mockito] Unused stubbings of: ").append(mock).append("\n"); 54 55 x = 1; 56 for (Stubbing s : stubbings) { 57 sb.append(" ").append(x++).append(". ").append(s.getInvocation()).append("\n"); 58 sb.append(" - stubbed ").append(s.getInvocation().getLocation()).append("\n"); 59 } 60 return sb.toString(); 61 } 62 } 63