griffon/test/MockClosureProxy.java

`MockClosureProxy.java`
`01 /* 02 * Copyright 2008-2012 the original author or authors. 03 * 04 * Licensed under the Apache License, Version 2.0 (the "License"); 05 * you may not use this file except in compliance with the License. 06 * You may obtain a copy of the License at 07 * 08 * http://www.apache.org/licenses/LICENSE-2.0 09 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package griffon.test; 17 18 import groovy.lang.Closure; 19 import groovy.mock.interceptor.LooseExpectation; 20 import groovy.mock.interceptor.StrictExpectation; 21 22 /** 23 * This closure proxy stores an expectation and checks it before each 24 * call to the target closure. It is used by the Griffon mocking framework. 25 * 26 * @author Peter Ledbrook (Grails 1.1) 27 */ 28 public class MockClosureProxy extends AbstractClosureProxy { 29 String methodName; 30 Object expectation; 31 32 /** 33 * Constructor. 34 * @param target 35 * @param methodName 36 * @param expectation 37 */ 38 public MockClosureProxy(Closure target, String methodName, Object expectation) { 39 super(target); 40 this.methodName = methodName; 41 this.expectation = expectation; 42 43 if (!(expectation instanceof LooseExpectation) && !(expectation instanceof StrictExpectation)) { 44 throw new IllegalArgumentException( 45 "Expectation must be either groovy.mock.interceptor.LooseExpectation or " + 46 " groovy.mock.interceptor.StrictExpectation (actual class: " + 47 expectation.getClass() + ")"); 48 } 49 } 50 51 /** 52 * Checks whether the target "method" is expected or not, on the 53 * basis that this closure is mocking a method with the name 54 * <code>methodName</code>. 55 * @param args The arguments to the "method" (actually 56 * the argumetns to the target closure invocation). 57 */ 58 @Override 59 protected void doBeforeCall(Object[] args) { 60 if (expectation instanceof LooseExpectation) { 61 ((LooseExpectation) expectation).match(methodName); 62 } 63 else { 64 ((StrictExpectation) expectation).match(methodName); 65 } 66 } 67 68 /** 69 * Empty implementation. 70 * @param args The arguments to the target closure. 71 */ 72 @Override 73 protected void doAfterCall(Object[] args) { 74 // do nothing 75 } 76 77 /** 78 * Creates a new <code>MockClosureProxy</code> wrapping the given 79 * closure. 80 * @param c The closure to wrap. 81 * @return the new proxy. 82 */ 83 @Override 84 protected Closure createWrapper(Closure c) { 85 return new MockClosureProxy(c, methodName, expectation); 86 } 87 }`