当条件达到javatestng时,完成测试用例方法



我有一个测试方法,它启动GUI窗口,然后开始一个无休止的循环。我想在GUI关闭时完成测试方法。有什么想法吗?我尝试设置一个boolean变量,当按下退出按钮时,我将其更改为false,这样循环应该结束,但当我查看日志时,测试状态已启动。

boolean testRunning = true;
JButton buttonQuit;
@Test
public void start() {
    MainFrame.getInstance().setVisible(true);
    if (showHelpDialog) {
        HelpDialog.getInstance().setVisible(true);
    }
    while(testRunning) {
    }
}

当我按下退出按钮时,testRunning变量被设置为false。

我认为你的问题是,你通过执行循环来用UI阻塞线程。

我用JFrame做了一个小例子。这个框架有一个和框架一样大的JButton。在按下按钮之前,线程正在和循环工作:

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Test {
    //to setThe state of the loop
    public static boolean continueLoop = true;
    public static void main(String[] args) {
        //Create a Frame
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        Dimension d = new Dimension(400, 400);
        frame.setSize(d);
        //Add a button to close the programm or end the loop
        JButton b = new JButton("Close");
        b.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                continueLoop = false;
                //Enable this if you want to close the programm
                //System.exit(0);
            }
        });
        // Start a Thread with your endless loop in it
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                int i = 1;
                while(continueLoop)
                {
                    try {
                        Thread.sleep(500);
                        System.out.println("Try: " + i);
                        i++;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t.start();
        // Add a button and set de Frame visible
        frame.add(b);       
        frame.setVisible(true);
    }
}

希望能有所帮助!

附言:这是我能想到的最快的例子。请注意,有更好的方法可以将状态控制的循环添加到UI中。例如,我在示例中使用了静态变量——除非真的有必要,否则不应该在应用程序中这样做。

最新更新