01: package groovy.mock;
02:
03: import groovy.lang.GroovyObject;
04: import groovy.lang.Closure;
05: import groovy.lang.GroovyObjectSupport;
06:
07: import com.mockobjects.Verifiable;
08: import com.mockobjects.dynamic.*;
09:
10: /**
11: *
12: * @author Joe Walnes
13: * @author Chris Stevenson
14: * @version $Revision: 2910 $
15: */
16: public class GroovyMock extends GroovyObjectSupport implements
17: Verifiable {
18:
19: private CallBag calls = new CallBag();
20: private CallFactory callFactory = new DefaultCallFactory();
21: private Mock mock = new Mock(I.class);
22:
23: interface I {
24: }
25:
26: private GroovyObject instance = new GroovyObjectSupport() {
27: public Object invokeMethod(String name, Object args) {
28: return callMethod(name, args);
29: }
30: };
31:
32: public Object invokeMethod(String name, Object args) {
33: if (name.equals("verify")) {
34: verify();
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(callFactory.createCallExpectation(callFactory
52: .createCallSignature(name, constraintMatcher,
53: 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: } catch (Throwable throwable) {
71: throw new RuntimeException(throwable);
72: }
73: }
74:
75: public void verify() {
76: calls.verify();
77: }
78:
79: }
|