KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > groovy > mock > GroovyMock


1 package groovy.mock;
2
3 import groovy.lang.GroovyObject;
4 import groovy.lang.Closure;
5 import groovy.lang.GroovyObjectSupport;
6
7 import com.mockobjects.Verifiable;
8 import com.mockobjects.dynamic.*;
9
10 /**
11  *
12  * @author Joe Walnes
13  * @author Chris Stevenson
14  * @version $Revision: 1.2 $
15  */

16 public class GroovyMock extends GroovyObjectSupport implements Verifiable {
17
18     private CallBag calls = new CallBag();
19     private CallFactory callFactory = new DefaultCallFactory();
20     private Mock mock = new Mock(I.class);
21
22     interface I {
23     }
24
25     private GroovyObject instance = new GroovyObjectSupport() {
26         public Object JavaDoc invokeMethod(String JavaDoc name, Object JavaDoc args) {
27             return callMethod(name, args);
28         }
29     };
30
31     public Object JavaDoc invokeMethod(String JavaDoc name, Object JavaDoc args) {
32         if (name.equals("verify")) {
33             verify();
34         }
35         else {
36             expectMethod(name, args);
37         }
38         return null;
39     }
40
41     public GroovyObject getInstance() {
42         return instance;
43     }
44
45     public static GroovyMock newInstance() {
46         return new GroovyMock();
47     }
48
49     private void expectMethod(String JavaDoc name, Object JavaDoc args) {
50         ConstraintMatcher constraintMatcher = createMatcher(args);
51         calls.addExpect(
52             callFactory.createCallExpectation(
53                 callFactory.createCallSignature(name, constraintMatcher, callFactory.createVoidStub())));
54     }
55
56     private ConstraintMatcher createMatcher(Object JavaDoc args) {
57         if(args.getClass().isArray()) {
58             Object JavaDoc argArray[] = (Object JavaDoc[]) args;
59             if (argArray[0] instanceof Closure) {
60                 Closure closure = (Closure) argArray[0];
61                 return C.args(new ClosureConstraintMatcher(closure));
62             }
63         }
64         return C.args(C.eq(args));
65     }
66
67     private Object JavaDoc callMethod(String JavaDoc name, Object JavaDoc args) {
68         try {
69             return calls.call(mock, name, new Object JavaDoc[] { args });
70         }
71         catch (Throwable JavaDoc throwable) {
72             throw new RuntimeException JavaDoc(throwable);
73         }
74     }
75
76     public void verify() {
77         calls.verify();
78     }
79
80 }
81
Popular Tags