View Javadoc

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.4 $
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 invokeMethod(String name, Object args) {
27              return callMethod(name, args);
28          }
29      };
30  
31      public Object invokeMethod(String name, Object 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 name, Object 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 args) {
57          if(args.getClass().isArray()) {
58              Object argArray[] = (Object[]) 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 callMethod(String name, Object args) {
68          try {
69              return calls.call(mock, name, new Object[] { args });
70          }
71          catch (Throwable throwable) {
72              throw new RuntimeException(throwable);
73          }
74      }
75  
76      public void verify() {
77          calls.verify();
78      }
79  
80  }