1 /*
2  * Written by Doug Lea with assistance from members of JCP JSR-166
3  * Expert Group and released to the public domain, as explained at
4  * http://creativecommons.org/publicdomain/zero/1.0/
5  * Other contributors include Andrew Wright, Jeffrey Hayes,
6  * Pat Fisher, Mike Judd.
7  */
8 
9 package jsr166;
10 
11 import junit.framework.*;
12 
13 public class ThreadTest extends JSR166TestCase {
14 
15     static class MyHandler implements Thread.UncaughtExceptionHandler {
uncaughtException(Thread t, Throwable e)16         public void uncaughtException(Thread t, Throwable e) {
17             e.printStackTrace();
18         }
19     }
20 
21     /**
22      * getUncaughtExceptionHandler returns ThreadGroup unless set,
23      * otherwise returning value of last setUncaughtExceptionHandler.
24      */
testGetAndSetUncaughtExceptionHandler()25     public void testGetAndSetUncaughtExceptionHandler() {
26         // these must be done all at once to avoid state
27         // dependencies across tests
28         Thread current = Thread.currentThread();
29         ThreadGroup tg = current.getThreadGroup();
30         MyHandler eh = new MyHandler();
31         assertEquals(tg, current.getUncaughtExceptionHandler());
32         current.setUncaughtExceptionHandler(eh);
33         assertEquals(eh, current.getUncaughtExceptionHandler());
34         current.setUncaughtExceptionHandler(null);
35         assertEquals(tg, current.getUncaughtExceptionHandler());
36     }
37 
38     /**
39      * getDefaultUncaughtExceptionHandler returns value of last
40      * setDefaultUncaughtExceptionHandler.
41      */
testGetAndSetDefaultUncaughtExceptionHandler()42     public void testGetAndSetDefaultUncaughtExceptionHandler() {
43         // BEGIN android-remove (when running as cts the RuntimeInit will
44         // set a default handler)
45         // assertEquals(null, Thread.getDefaultUncaughtExceptionHandler());
46         // END android-remove
47 
48         // failure due to securityException is OK.
49         // Would be nice to explicitly test both ways, but cannot yet.
50         try {
51             Thread current = Thread.currentThread();
52             ThreadGroup tg = current.getThreadGroup();
53             MyHandler eh = new MyHandler();
54             Thread.setDefaultUncaughtExceptionHandler(eh);
55             assertEquals(eh, Thread.getDefaultUncaughtExceptionHandler());
56             Thread.setDefaultUncaughtExceptionHandler(null);
57         }
58         catch (SecurityException ok) {
59         }
60         assertEquals(null, Thread.getDefaultUncaughtExceptionHandler());
61     }
62 
63     // How to test actually using UEH within junit?
64 
65 }
66