KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jmock > core > LIFOInvocationDispatcher


1 /* Copyright (c) 2000-2004 jMock.org
2  */

3 package org.jmock.core;
4
5 import java.util.ArrayList JavaDoc;
6 import java.util.Iterator JavaDoc;
7 import java.util.ListIterator JavaDoc;
8 import org.jmock.core.stub.TestFailureStub;
9
10
11 public class LIFOInvocationDispatcher
12         implements InvocationDispatcher
13 {
14     public static final String JavaDoc NO_EXPECTATIONS_MESSAGE = "No expectations set";
15
16     private ArrayList JavaDoc invokables = new ArrayList JavaDoc();
17     private Stub defaultStub = new TestFailureStub("no match found");
18
19     public Object JavaDoc dispatch( Invocation invocation ) throws Throwable JavaDoc {
20         ListIterator JavaDoc i = invokables.listIterator(invokables.size());
21         while (i.hasPrevious()) {
22             Invokable invokable = (Invokable)i.previous();
23             if (invokable.matches(invocation)) {
24                 return invokable.invoke(invocation);
25             }
26         }
27
28         return defaultStub.invoke(invocation);
29     }
30
31     public void setDefaultStub( Stub defaultStub ) {
32         this.defaultStub = defaultStub;
33     }
34
35     public void add( Invokable invokable ) {
36         invokables.add(invokable);
37     }
38
39     public void verify() {
40         Iterator JavaDoc i = invokables.iterator();
41         while (i.hasNext()) {
42             ((Verifiable)i.next()).verify();
43         }
44     }
45
46     public void clear() {
47         invokables.clear();
48     }
49
50     public StringBuffer JavaDoc describeTo( StringBuffer JavaDoc buffer ) {
51         if (anyInvokableHasDescription()) {
52             writeInvokablesTo(buffer);
53         } else {
54             buffer.append(NO_EXPECTATIONS_MESSAGE);
55         }
56
57         return buffer;
58     }
59
60     private void writeInvokablesTo( StringBuffer JavaDoc buffer ) {
61         Iterator JavaDoc iterator = invokables.iterator();
62         while (iterator.hasNext()) {
63             Invokable invokable = (Invokable)iterator.next();
64             if (invokable.hasDescription()) {
65                 invokable.describeTo(buffer).append("\n");
66             }
67         }
68     }
69
70     private boolean anyInvokableHasDescription() {
71         Iterator JavaDoc iterator = invokables.iterator();
72         while (iterator.hasNext()) {
73             if (((Invokable)iterator.next()).hasDescription()) return true;
74         }
75         return false;
76     }
77 }
78
Popular Tags