KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sleepycat > je > junit > JUnitThread


1 /*-
2  * See the file LICENSE for redistribution information.
3  *
4  * Copyright (c) 2002,2006 Oracle. All rights reserved.
5  *
6  * $Id: JUnitThread.java,v 1.19 2006/10/30 21:14:45 bostic Exp $
7  */

8
9 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 JavaDoc {
40     private Throwable JavaDoc errorReturn;
41
42     /**
43      * Construct a new JUnitThread.
44      */

45     public JUnitThread(String JavaDoc name) {
46     super(name);
47     }
48
49     public void run() {
50     try {
51         testBody();
52     } catch (Throwable JavaDoc 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()
63     throws Throwable JavaDoc {
64
65     }
66
67     /**
68      * This method should be called after the JUnitThread has been
69      * constructed to cause the actual test to be run and any failures
70      * to be returned.
71      */

72     public void doTest()
73     throws Throwable JavaDoc {
74
75     start();
76         finishTest();
77     }
78
79     /**
80      * This method should be called after the JUnitThread has been
81      * started to cause the test to report any failures.
82      */

83     public void finishTest()
84     throws Throwable JavaDoc {
85
86     try {
87         join();
88     } catch (InterruptedException JavaDoc IE) {
89         Assert.fail("caught unexpected InterruptedException");
90     }
91     if (errorReturn != null) {
92         throw errorReturn;
93     }
94     }
95
96     public String JavaDoc toString() {
97     return "<JUnitThread: " + super.toString() + ">";
98     }
99 }
100
Popular Tags