1 3 package org.jmock.core; 4 5 import java.util.ArrayList ; 6 import java.util.Collections ; 7 import java.util.Iterator ; 8 import java.util.List ; 9 import junit.framework.AssertionFailedError; 10 import org.jmock.core.stub.VoidStub; 11 12 13 public class InvocationMocker 14 implements Invokable, StubMatchersCollection 15 { 16 public interface Describer 17 { 18 public boolean hasDescription(); 19 20 public void describeTo( StringBuffer buffer, 21 List matchers, Stub stub, String name ); 22 } 23 24 private String name = null; 25 private List matchers = new ArrayList (); 26 private Stub stub = VoidStub.INSTANCE; 27 private Describer describer; 28 29 30 public InvocationMocker() { 31 this(DEFAULT_DESCRIBER); 32 } 33 34 public InvocationMocker( Describer describer ) { 35 this.describer = describer; 36 } 37 38 public boolean matches( Invocation invocation ) { 39 Iterator i = matchers.iterator(); 40 while (i.hasNext()) { 41 if (!((InvocationMatcher)i.next()).matches(invocation)) { 42 return false; 43 } 44 } 45 return true; 46 } 47 48 public Object invoke( Invocation invocation ) throws Throwable { 49 Iterator i = matchers.iterator(); 50 while (i.hasNext()) { 51 ((InvocationMatcher)i.next()).invoked(invocation); 52 } 53 return stub.invoke(invocation); 54 } 55 56 public void verify() { 57 try { 58 Iterator i = matchers.iterator(); 59 while (i.hasNext()) { 60 ((InvocationMatcher)i.next()).verify(); 61 } 62 } 63 catch (AssertionFailedError error) { 64 AssertionFailedError newError = new AssertionFailedError(error.getMessage() + "\n" + toString()); 65 newError.fillInStackTrace(); 66 throw newError; 67 } 68 } 69 70 public void setName( String name ) { 71 this.name = name; 72 } 73 74 public void addMatcher( InvocationMatcher matcher ) { 75 matchers.add(matcher); 76 } 77 78 public void setStub( Stub stub ) { 79 this.stub = stub; 80 } 81 82 public String toString() { 83 return describeTo(new StringBuffer ()).toString(); 84 } 85 86 public boolean hasDescription() { 87 return describer.hasDescription(); 88 } 89 90 public StringBuffer describeTo( StringBuffer buffer ) { 91 describer.describeTo(buffer, 92 Collections.unmodifiableList(matchers), 93 stub, 94 name); 95 96 return buffer; 97 } 98 99 public static final Describer DEFAULT_DESCRIBER = new Describer() 100 { 101 public boolean hasDescription() { 102 return true; 103 } 104 105 public void describeTo( StringBuffer buffer, 106 List matchers, Stub stub, String name ) { 107 Iterator it = matchers.iterator(); 108 while (it.hasNext()) { 109 InvocationMatcher matcher = (InvocationMatcher)it.next(); 110 111 if (matcher.hasDescription()) { 112 matcher.describeTo(buffer).append(", "); 113 } 114 } 115 116 stub.describeTo(buffer); 117 118 if (name != null) { 119 buffer.append(" [").append(name).append("]"); 120 } 121 } 122 }; 123 } 124 | Popular Tags |