01: /*-
02: * See the file LICENSE for redistribution information.
03: *
04: * Copyright (c) 2002,2008 Oracle. All rights reserved.
05: *
06: * $Id: JUnitThread.java,v 1.19.2.2 2008/01/07 15:14:28 cwl Exp $
07: */
08:
09: package com.sleepycat.je.junit;
10:
11: import junit.framework.Assert;
12:
13: /**
14: * JUnitThread is a utility class that allows JUtil assertions to be
15: * run in other threads. A JUtil assertion thrown from a
16: * thread other than the invoking one can not be caught by JUnit.
17: * This class allows these AssertionFailedErrors to be caught and
18: * passed back to the original thread.
19: * <p>
20: * To use, create a JUnitThread and override the testBody() method with
21: * the test code. Then call doTest() on the thread to run the test
22: * and re-throw any assertion failures that were thrown by the
23: * subthread.
24: * <p>
25: * Example:
26: * <pre>
27: public void testEquality() {
28: JUnitThread tester =
29: new JUnitThread("testEquality") {
30: public void testBody() {
31: int one = 1;
32: assertTrue(one == 1);
33: }
34: };
35: tester.doTest();
36: }
37: * </pre>
38: */
39: public class JUnitThread extends Thread {
40: private Throwable errorReturn;
41:
42: /**
43: * Construct a new JUnitThread.
44: */
45: public JUnitThread(String name) {
46: super (name);
47: }
48:
49: public void run() {
50: try {
51: testBody();
52: } catch (Throwable T) {
53: errorReturn = T;
54: }
55: }
56:
57: /**
58: * Method that is to be overridden by the user. Code should be
59: * the guts of the test. assertXXXX() methods may be called in
60: * this method.
61: */
62: public void testBody() throws Throwable {
63:
64: }
65:
66: /**
67: * This method should be called after the JUnitThread has been
68: * constructed to cause the actual test to be run and any failures
69: * to be returned.
70: */
71: public void doTest() throws Throwable {
72:
73: start();
74: finishTest();
75: }
76:
77: /**
78: * This method should be called after the JUnitThread has been
79: * started to cause the test to report any failures.
80: */
81: public void finishTest() throws Throwable {
82:
83: try {
84: join();
85: } catch (InterruptedException IE) {
86: Assert.fail("caught unexpected InterruptedException");
87: }
88: if (errorReturn != null) {
89: throw errorReturn;
90: }
91: }
92:
93: public String toString() {
94: return "<JUnitThread: " + super .toString() + ">";
95: }
96: }
|