1 3 package org.jmock.core.stub; 4 5 import junit.framework.Assert; 6 import org.jmock.core.Invocation; 7 import org.jmock.core.Stub; 8 9 10 public class ThrowStub 11 extends Assert 12 implements Stub 13 { 14 private Throwable throwable; 15 16 public ThrowStub( Throwable throwable ) { 17 this.throwable = throwable; 18 } 19 20 public Object invoke( Invocation invocation ) throws Throwable { 21 if (isThrowingCheckedException()) { 22 checkTypeCompatiblity(invocation.invokedMethod.getExceptionTypes()); 23 } 24 25 throwable.fillInStackTrace(); 26 throw throwable; 27 } 28 29 public StringBuffer describeTo( StringBuffer buffer ) { 30 return buffer.append("throws <").append(throwable).append(">"); 31 } 32 33 private void checkTypeCompatiblity( Class [] allowedExceptionTypes ) { 34 for (int i = 0; i < allowedExceptionTypes.length; i++) { 35 if (allowedExceptionTypes[i].isInstance(throwable)) return; 36 } 37 38 reportIncompatibleCheckedException(allowedExceptionTypes); 39 } 40 41 private void reportIncompatibleCheckedException( Class [] allowedTypes ) { 42 StringBuffer message = new StringBuffer (); 43 44 message.append("tried to throw a "); 45 message.append(throwable.getClass().getName()); 46 message.append(" from a method that throws "); 47 48 if (allowedTypes.length == 0) { 49 message.append("no exceptions"); 50 } else { 51 for (int i = 0; i < allowedTypes.length; i++) { 52 if (i > 0) message.append(","); 53 message.append(allowedTypes[i].getName()); 54 } 55 } 56 57 fail(message.toString()); 58 } 59 60 private boolean isThrowingCheckedException() { 61 return !(throwable instanceof RuntimeException || throwable instanceof Error ); 62 } 63 } 64 | Popular Tags |