001 package groovy.mock;
002
003 import groovy.lang.GroovyObject;
004 import groovy.lang.Closure;
005 import groovy.lang.GroovyObjectSupport;
006
007 import com.mockobjects.Verifiable;
008 import com.mockobjects.dynamic.*;
009
010 /**
011 *
012 * @author Joe Walnes
013 * @author Chris Stevenson
014 * @version $Revision: 1.2 $
015 */
016 public class GroovyMock extends GroovyObjectSupport implements Verifiable {
017
018 private CallBag calls = new CallBag();
019 private CallFactory callFactory = new DefaultCallFactory();
020 private Mock mock = new Mock(I.class);
021
022 interface I {
023 }
024
025 private GroovyObject instance = new GroovyObjectSupport() {
026 public Object invokeMethod(String name, Object args) {
027 return callMethod(name, args);
028 }
029 };
030
031 public Object invokeMethod(String name, Object args) {
032 if (name.equals("verify")) {
033 verify();
034 }
035 else {
036 expectMethod(name, args);
037 }
038 return null;
039 }
040
041 public GroovyObject getInstance() {
042 return instance;
043 }
044
045 public static GroovyMock newInstance() {
046 return new GroovyMock();
047 }
048
049 private void expectMethod(String name, Object args) {
050 ConstraintMatcher constraintMatcher = createMatcher(args);
051 calls.addExpect(
052 callFactory.createCallExpectation(
053 callFactory.createCallSignature(name, constraintMatcher, callFactory.createVoidStub())));
054 }
055
056 private ConstraintMatcher createMatcher(Object args) {
057 if(args.getClass().isArray()) {
058 Object argArray[] = (Object[]) args;
059 if (argArray[0] instanceof Closure) {
060 Closure closure = (Closure) argArray[0];
061 return C.args(new ClosureConstraintMatcher(closure));
062 }
063 }
064 return C.args(C.eq(args));
065 }
066
067 private Object callMethod(String name, Object args) {
068 try {
069 return calls.call(mock, name, new Object[] { args });
070 }
071 catch (Throwable throwable) {
072 throw new RuntimeException(throwable);
073 }
074 }
075
076 public void verify() {
077 calls.verify();
078 }
079
080 }