1 5 package org.easymock.internal; 6 7 import java.lang.reflect.Method ; 8 import java.util.HashMap ; 9 import java.util.Map ; 10 11 import junit.framework.AssertionFailedError; 12 13 import org.easymock.ArgumentsMatcher; 14 import org.easymock.MockControl; 15 16 public abstract class AbstractBehavior implements IBehavior { 17 private ArgumentsMatcher defaultMatcher; 18 19 private boolean defaultMatcherSet; 20 21 private Map <Method , ArgumentsMatcher> matchers = new HashMap <Method , ArgumentsMatcher>(); 22 23 private Map <Method , Result> defaultResults = new HashMap <Method , Result>(); 24 25 public void setDefaultMatcher(ArgumentsMatcher matcher) { 26 if (defaultMatcherSet) { 27 throw new RuntimeExceptionWrapper( 28 new IllegalStateException ( 29 "default matcher can only be set once directly after creation of the MockControl")); 30 } 31 defaultMatcher = matcher; 32 defaultMatcherSet = true; 33 } 34 35 public void setMatcher(Method method, ArgumentsMatcher matcher) { 36 if (matchers.containsKey(method) && matchers.get(method) != matcher) { 37 throw new RuntimeExceptionWrapper(new IllegalStateException ( 38 "for method " 39 + method.getName() 40 + "(" 41 + (method.getParameterTypes().length == 0 ? "" 42 : "...") 43 + "), a matcher has already been set")); 44 } 45 matchers.put(method, matcher); 46 } 47 48 public void setDefaultResult(Method method, Result result) { 49 defaultResults.put(method, result); 50 } 51 52 public final Result addActual(MethodCall methodCall) { 53 try { 54 return doAddActual(methodCall); 55 } catch (AssertionFailedErrorWrapper e) { 56 throw new AssertionFailedErrorWrapper(new AssertionFailedError( 57 "\n Unexpected method call " + methodCall.toString(getMatcher(methodCall.getMethod())) + ":" 58 + e.getAssertionFailedError().getMessage())); 59 } 60 } 61 62 public final void verify() { 63 try { 64 doVerify(); 65 } catch (AssertionFailedErrorWrapper e) { 66 throw new AssertionFailedErrorWrapper(new AssertionFailedError( 67 "\n Expectation failure on verify:" 68 + e.getAssertionFailedError().getMessage())); 69 } 70 } 71 72 protected Result getDefaultResult(Method method) { 73 return defaultResults.get(method); 74 } 75 76 protected ArgumentsMatcher getMatcher(Method method) { 77 if (!matchers.containsKey(method)) { 78 if (!defaultMatcherSet) { 79 setDefaultMatcher(MockControl.EQUALS_MATCHER); 80 } 81 matchers.put(method, defaultMatcher); 82 } 83 return matchers.get(method); 84 } 85 86 protected abstract void doVerify(); 87 88 protected abstract Result doAddActual(MethodCall methodCall); 89 } 90 | Popular Tags |