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.1 $
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 instanceof Closure) {
58 Closure closure = (Closure) args;
59 return C.args(new ClosureConstraintMatcher(closure));
60 }
61 else {
62 return C.args(C.eq(args));
63 }
64 }
65
66 private Object callMethod(String name, Object args) {
67 try {
68 return calls.call(mock, name, new Object[] { args });
69 }
70 catch (Throwable throwable) {
71 throw new RuntimeException(throwable);
72 }
73 }
74
75 public void verify() {
76 calls.verify();
77 }
78
79 }