KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mockobjects > dynamic > CallBag


1 /*
2  * Created on 04-Apr-2003
3  */

4 package com.mockobjects.dynamic;
5
6 import java.util.ArrayList JavaDoc;
7 import java.util.Iterator JavaDoc;
8 import java.util.List JavaDoc;
9
10
11 public class CallBag extends CallCollection implements Callable, CallableAddable {
12     private List JavaDoc expectedCalls = new ArrayList JavaDoc();
13     private List JavaDoc expectedMatches = new ArrayList JavaDoc();
14
15     public CallBag() {
16     }
17
18     public void reset() {
19         this.expectedCalls.clear();
20         this.expectedMatches.clear();
21     }
22
23     public Object JavaDoc call(Mock mock, String JavaDoc methodName, Object JavaDoc[] args)
24         throws Throwable JavaDoc {
25             
26         Callable matchingCall = findMatchingCall(methodName, args, this.expectedCalls);
27         if(matchingCall == null) {
28             matchingCall = findMatchingCall(methodName, args, this.expectedMatches);
29         }
30         if(matchingCall == null) {
31             throw createUnexpectedCallError(methodName, args);
32         }
33         
34         return matchingCall.call(mock, methodName, args);
35         
36     }
37
38     private Callable findMatchingCall(String JavaDoc methodName, Object JavaDoc[] args, List JavaDoc callList) {
39         for (Iterator JavaDoc call = callList.iterator(); call.hasNext();) {
40             Callable element = (Callable) call.next();
41
42             if (element.matches(methodName, args)) {
43                 return element;
44             }
45         }
46
47         return null;
48     }
49
50     public String JavaDoc getDescription() {
51         if (this.expectedCalls.isEmpty()) {
52             return "no methods";
53         } else {
54             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
55
56             buf.append("one of:\n");
57
58             for (Iterator JavaDoc i = this.expectedCalls.iterator(); i.hasNext();) {
59                 buf.append(((Callable) i.next()).getDescription());
60                 buf.append("\n");
61             }
62
63             return buf.toString();
64         }
65     }
66
67     public boolean matches(String JavaDoc methodName, Object JavaDoc[] args) {
68         throw new Error JavaDoc("not implemented");
69     }
70
71     public void verify() {
72         for (Iterator JavaDoc call = this.expectedCalls.iterator(); call.hasNext();) {
73             Callable element = (Callable) call.next();
74             element.verify();
75         }
76     }
77
78     public void addExpect(Callable call) {
79         this.expectedCalls.add(call);
80     }
81
82     public void addMatch(Callable call) {
83         this.expectedMatches.add(call);
84     }
85 }
86
Popular Tags