1 3 package org.jmock.core.stub; 4 5 import java.lang.reflect.Array ; 6 import java.util.HashMap ; 7 import java.util.Iterator ; 8 import java.util.Map ; 9 import junit.framework.AssertionFailedError; 10 import org.jmock.core.CoreMock; 11 import org.jmock.core.Formatting; 12 import org.jmock.core.Invocation; 13 import org.jmock.core.Stub; 14 15 16 public class DefaultResultStub 17 implements Stub 18 { 19 private Map resultValuesByType = new HashMap (); 20 21 public DefaultResultStub() { 22 createDefaultResults(); 23 } 24 25 public StringBuffer describeTo( StringBuffer buf ) { 26 return buf.append("returns a default value"); 27 } 28 29 public void addResult( Class resultType, Object resultValue ) { 30 resultValuesByType.put(resultType, resultValue); 31 } 32 33 public Object invoke( Invocation invocation ) 34 throws Throwable 35 { 36 Class returnType = invocation.invokedMethod.getReturnType(); 37 38 if (resultValuesByType.containsKey(returnType)) { 39 return resultValuesByType.get(returnType); 40 } else if (returnType.isArray()) { 41 return Array.newInstance(returnType.getComponentType(), 0); 42 } else if (returnType.isInterface()) { 43 CoreMock nullMock = new CoreMock(returnType, "null" + Formatting.classShortName(returnType)); 44 nullMock.setDefaultStub(this); 45 return nullMock.proxy(); 46 } else { 47 throw new AssertionFailedError(createErrorMessage(invocation)); 48 } 49 } 50 51 public String createErrorMessage( Invocation call ) { 52 StringBuffer buf = new StringBuffer (); 53 54 buf.append("unexpected result type: "); 55 buf.append(call.invokedMethod.getReturnType().toString()); 56 buf.append("\n"); 57 58 59 if (resultValuesByType.isEmpty()) { 60 buf.append("no result types are registered!"); 61 } else { 62 buf.append("expected one of: "); 63 64 Iterator i = resultValuesByType.keySet().iterator(); 65 boolean separatorRequired = false; 66 67 while (i.hasNext()) { 68 if (separatorRequired) buf.append(", "); 69 buf.append(((Class )i.next()).getName()); 70 71 separatorRequired = true; 72 } 73 } 74 75 return buf.toString(); 76 } 77 78 protected void createDefaultResults() { 79 addResult(boolean.class, Boolean.FALSE); 80 addResult(void.class, null); 81 addResult(byte.class, new Byte ((byte)0)); 82 addResult(short.class, new Short ((short)0)); 83 addResult(int.class, new Integer (0)); 84 addResult(long.class, new Long (0L)); 85 addResult(char.class, new Character ('\0')); 86 addResult(float.class, new Float (0.0F)); 87 addResult(double.class, new Double (0.0)); 88 addResult(Boolean .class, Boolean.FALSE); 89 addResult(Byte .class, new Byte ((byte)0)); 90 addResult(Short .class, new Short ((short)0)); 91 addResult(Integer .class, new Integer (0)); 92 addResult(Long .class, new Long (0L)); 93 addResult(Character .class, new Character ('\0')); 94 addResult(Float .class, new Float (0.0F)); 95 addResult(Double .class, new Double (0.0)); 96 addResult(String .class, ""); 97 } 98 } 99 | Popular Tags |