01: // Copyright © 2002-2005 Canoo Engineering AG, Switzerland.
02: package com.canoo.webtest.self;
03:
04: import junit.framework.Assert;
05: import junit.framework.AssertionFailedError;
06:
07: /**
08: * Test helper that captures the strategy of asserting proper Exception throwing in production code.
09: */
10: public class ThrowAssert {
11:
12: public static void assertThrows(Class throwable,
13: String exceptionMessage, TestBlock block) {
14: assertThrows("", throwable, exceptionMessage, block);
15: }
16:
17: public static void assertThrows(String message, Class throwable,
18: String exceptionMessage, TestBlock block) {
19: final String result = assertThrows(message, throwable, block)
20: .getMessage();
21: if (!result.startsWith(exceptionMessage)) {
22: Assert.fail("The exception message is <" + result
23: + ">, it does not start with <" + exceptionMessage
24: + ">.");
25: }
26: }
27:
28: public static String assertThrows(Class throwable, TestBlock block) {
29: return assertThrows("", throwable, block).getMessage();
30: }
31:
32: public static Throwable assertThrows(String message,
33: Class throwable, TestBlock block) {
34: boolean expectedThrowableThrown = false;
35: String prefixedMessage = appendPrefix(message);
36: Throwable thrown = null;
37: try {
38: block.call();
39: } catch (final Throwable t) {
40: thrown = t;
41: expectedThrowableThrown = checkException(throwable, t,
42: prefixedMessage);
43: }
44: Assert.assertTrue(prefixedMessage + "failed to throw "
45: + throwable.getName(), expectedThrowableThrown);
46: return thrown;
47: }
48:
49: private static boolean checkException(Class throwable, Throwable t,
50: String prefixedMessage) {
51: boolean expectedThrowableThrown = throwable.isAssignableFrom(t
52: .getClass());
53: if (!expectedThrowableThrown) {
54: t.printStackTrace(System.out);
55: Assert.fail(prefixedMessage + "expected exception "
56: + throwable.getName() + " but was "
57: + t.getClass().getName());
58: }
59: return expectedThrowableThrown;
60: }
61:
62: private static String appendPrefix(String message) {
63: if (message.length() > 0)
64: return message + " :";
65: return message;
66: }
67:
68: public static void assertPasses(String message, TestBlock block) {
69: try {
70: block.call();
71: } catch (Throwable t) {
72: String fullMessage = appendPrefix(message)
73: + "should not have raised exception "
74: + t.getClass().getName();
75: AssertionFailedError junitError = new AssertionFailedError(
76: fullMessage);
77: junitError.setStackTrace(t.getStackTrace());
78: throw junitError;
79: }
80: }
81:
82: }
|