Source code: junit/extensions/abbot/ComponentTestFixture.java
1 package junit.extensions.abbot;
2
3 import junit.framework.*;
4 import java.awt.*;
5 import java.awt.event.*;
6 import javax.swing.*;
7 import javax.swing.border.*;
8 import abbot.*;
9
10 /** Simple wrapper for testing components under JUnit. Derived classes
11 * provide a component which is placed within a frame and displayed prior to
12 * each test.
13 */
14
15 public class ComponentTestFixture extends TestCase {
16
17 /** This method should be invoked to display the component under test.
18 * The frame's size will be its preferred size.
19 */
20 protected Frame showFrame(Component comp) {
21 return showFrame(comp, null);
22 }
23
24 private volatile boolean opened = false;
25 /** This method should be invoked to display the component under test,
26 * when a specific size of frame is desired.
27 */
28 protected Frame showFrame(Component comp, Dimension size) {
29 JFrame frame = new JFrame(getName());
30 JPanel pane = (JPanel)frame.getContentPane();
31 pane.setBorder(new EmptyBorder(10, 10, 10, 10));
32 pane.add(comp);
33 frame.addWindowListener(new WindowAdapter() {
34 public void windowOpened(WindowEvent ev) {
35 opened = true;
36 }
37 });
38 frame.pack();
39 if (size != null)
40 frame.setSize(size.width, size.height);
41 frame.show();
42 Timer timer = new Timer();
43 while (!opened) {
44 // Ensure the window is visible before returning
45 if (timer.elapsed() > 10000)
46 throw new RuntimeException("Timed out waiting for frame to show");
47 }
48 opened = false;
49 return frame;
50 }
51
52 /** Construct a test case with the given name. */
53 public ComponentTestFixture(String name) {
54 super(name);
55 }
56
57 /** Obtain a component finder to look up components. */
58 protected ComponentFinder getFinder() {
59 return DefaultComponentFinder.getFinder();
60 }
61
62 /** Override the default TestCase runTest method to ensure components are
63 * cleaned up after the test.
64 */
65 protected void runTest() throws Throwable {
66 // Don't interfere with any existing framework (e.g. JUnit gui)
67 getFinder().discardAllComponents();
68 try {
69 super.runTest();
70 }
71 finally {
72 getFinder().disposeWindows();
73 }
74 }
75 }