01: package abbot.util;
02:
03: import java.util.*;
04: import junit.extensions.abbot.Timer;
05: import junit.extensions.abbot.TestHelper;
06: import junit.framework.*;
07:
08: public class NamedTimerTest extends TestCase {
09:
10: private NamedTimer timer;
11:
12: protected void setUp() {
13: timer = new NamedTimer(getName(), true) {
14: protected void handleException(Throwable t) {
15: }
16: };
17: }
18:
19: protected void tearDown() {
20: timer.cancel();
21: }
22:
23: public void testSetName() throws Exception {
24: class Flag {
25: volatile String name;
26: }
27: final Flag flag = new Flag();
28: timer.schedule(new TimerTask() {
29: public void run() {
30: flag.name = Thread.currentThread().getName();
31: }
32: }, 0);
33: Timer t = new Timer();
34: while (flag.name == null) {
35: if (t.elapsed() > 5000)
36: fail("Task never ran");
37: try {
38: Thread.sleep(50);
39: } catch (InterruptedException e) {
40: }
41: Thread.yield();
42: }
43: assertEquals("Thread not properly named", getName(), flag.name);
44: }
45:
46: public void testExceptionThrowingTimerTask() throws Exception {
47: class Flag {
48: volatile boolean taskRan;
49: }
50: final Flag flag = new Flag();
51: TimerTask task = new TimerTask() {
52: public void run() {
53: try {
54: throw new RuntimeException("Purposely throwing");
55: } finally {
56: flag.taskRan = true;
57: }
58: }
59: };
60: timer.schedule(task, 0);
61: Timer t = new Timer();
62: while (!flag.taskRan) {
63: if (t.elapsed() > 5000)
64: fail("Task never ran");
65: Thread.yield();
66: }
67: // This will throw an exception if the Timer was canceled
68: timer.schedule(new TimerTask() {
69: public void run() {
70: }
71: }, 0);
72: }
73:
74: public void testCancelTask() throws Exception {
75: class Flag {
76: volatile boolean taskRan;
77: }
78: final Flag flag = new Flag();
79: TimerTask task = new TimerTask() {
80: public void run() {
81: flag.taskRan = true;
82: }
83: };
84: timer.schedule(task, 100);
85: task.cancel();
86: Thread.sleep(200);
87: assertTrue("Task should not have run", !flag.taskRan);
88: }
89:
90: public NamedTimerTest(String name) {
91: super (name);
92: }
93:
94: public static void main(String[] args) {
95: TestHelper.runTests(args, NamedTimerTest.class);
96: }
97: }
|