1 3 package org.jmock.core.stub; 4 5 import java.util.HashMap ; 6 import java.util.Map ; 7 import junit.framework.Assert; 8 import org.jmock.core.Invocation; 9 import org.jmock.core.Stub; 10 11 12 public class ReturnStub 13 extends Assert 14 implements Stub 15 { 16 private Object result; 17 18 private static Map BOX_TYPES = new HashMap (); 19 20 static { 21 BOX_TYPES.put(boolean.class, Boolean .class); 22 BOX_TYPES.put(byte.class, Byte .class); 23 BOX_TYPES.put(char.class, Character .class); 24 BOX_TYPES.put(short.class, Short .class); 25 BOX_TYPES.put(int.class, Integer .class); 26 BOX_TYPES.put(long.class, Long .class); 27 BOX_TYPES.put(float.class, Float .class); 28 BOX_TYPES.put(double.class, Double .class); 29 } 30 31 32 public ReturnStub( Object result ) { 33 this.result = result; 34 } 35 36 public Object invoke( Invocation invocation ) throws Throwable { 37 checkTypeCompatiblity(invocation.invokedMethod.getReturnType()); 38 return result; 39 } 40 41 public StringBuffer describeTo( StringBuffer buffer ) { 42 return buffer.append("returns <").append(result).append(">"); 43 } 44 45 private void checkTypeCompatiblity( Class returnType ) { 46 if (result == null) { 47 if (returnType.isPrimitive()) reportInvalidNullValue(returnType); 48 } else if (returnType == void.class) { 49 reportReturnFromVoidMethod(); 50 } else { 51 Class valueType = result.getClass(); 52 if (!isCompatible(returnType, valueType)) { 53 reportTypeError(returnType, valueType); 54 } 55 } 56 } 57 58 private boolean isCompatible( Class returnType, Class valueType ) { 59 if (returnType.isPrimitive()) { 60 return isBoxedType(returnType, valueType); 61 } 62 return returnType.isAssignableFrom(valueType); 63 } 64 65 private boolean isBoxedType( Class primitiveType, Class referenceType ) { 66 return BOX_TYPES.get(primitiveType) == referenceType; 67 } 68 69 private void reportTypeError( Class returnType, Class valueType ) { 70 fail("tried to return an incompatible value: " + 71 "expected a " + returnType + " but returned a " + valueType); 72 } 73 74 private void reportInvalidNullValue( Class returnType ) { 75 fail("tried to return null value from invokedMethod returning " + returnType); 76 } 77 78 private void reportReturnFromVoidMethod() { 79 fail("tried to return a value from a void method"); 80 } 81 } 82 | Popular Tags |