1 package com.mockobjects.dynamic; 2 3 import java.util.ArrayList ; 4 import java.util.Iterator ; 5 6 import junit.framework.AssertionFailedError; 7 8 public class CallSequence extends CallCollection implements Callable, CallableAddable { 9 10 private ArrayList expectedCalls = new ArrayList (); 11 private CallBag matchedCalls = new CallBag(); 12 int callIndex = 0; 13 14 public void reset() 15 { 16 this.expectedCalls.clear(); 17 this.matchedCalls.reset(); 18 } 19 20 public Object call(Mock mock, String methodName, Object [] args) throws Throwable { 21 if (expectedCalls.size() == 0) throw new AssertionFailedError("no methods defined on mock, received: " + DynamicUtil.methodToString(methodName, args)); 22 if (callIndex == expectedCalls.size()) throw new AssertionFailedError("mock called too many times, received: " + DynamicUtil.methodToString(methodName, args)); 23 24 Callable nextCall = (Callable)expectedCalls.get(callIndex++); 25 if (nextCall.matches(methodName, args)) 26 return nextCall.call(mock, methodName, args); 27 28 try { 29 return matchedCalls.call(mock, methodName, args); 30 } catch (AssertionFailedError ex) { 31 throw createUnexpectedCallError(methodName, args); 32 } 33 } 34 35 public String getDescription() { 36 if (expectedCalls.isEmpty()) { 37 return "no methods"; 38 } else { 39 StringBuffer buf = new StringBuffer (); 40 41 buf.append("in sequence:\n"); 42 43 int j=0; 44 for (Iterator i = expectedCalls.iterator(); i.hasNext();) { 45 buf.append(((Callable)i.next()).getDescription()); 46 if (j++==(callIndex-1)) buf.append(" <<< Next Expected Call"); 47 buf.append("\n"); 48 } 49 50 return buf.toString(); 51 } 52 } 53 54 public boolean matches(String methodName, Object [] args) { 55 throw new AssertionFailedError("matches() operation not supported in CallSequence"); 56 } 57 58 public void addExpect(Callable call) { 59 expectedCalls.add(call); 60 } 61 62 public void addMatch(Callable call) { 63 matchedCalls.addMatch(call); 64 } 65 66 public void verify() { 67 for (Iterator iter = expectedCalls.iterator(); iter.hasNext();) { 68 Callable callable = (Callable) iter.next(); 69 callable.verify(); 70 } 71 } 72 73 } 74 | Popular Tags |