KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jmock > core > stub > ThrowStub


1 /* Copyright (c) 2000-2004 jMock.org
2  */

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 JavaDoc throwable;
15
16     public ThrowStub( Throwable JavaDoc throwable ) {
17         this.throwable = throwable;
18     }
19
20     public Object JavaDoc invoke( Invocation invocation ) throws Throwable JavaDoc {
21         if (isThrowingCheckedException()) {
22             checkTypeCompatiblity(invocation.invokedMethod.getExceptionTypes());
23         }
24
25         throwable.fillInStackTrace();
26         throw throwable;
27     }
28
29     public StringBuffer JavaDoc describeTo( StringBuffer JavaDoc buffer ) {
30         return buffer.append("throws <").append(throwable).append(">");
31     }
32
33     private void checkTypeCompatiblity( Class JavaDoc[] 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 JavaDoc[] allowedTypes ) {
42         StringBuffer JavaDoc message = new StringBuffer JavaDoc();
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 JavaDoc || throwable instanceof Error JavaDoc);
62     }
63 }
64
Popular Tags