我有测试方法,它启动 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。
最佳答案
我认为你的问题是,你通过执行循环来阻塞用户界面的线程。
我用 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);
}
}
希望有帮助!
PS:这是我能想到的最快的例子。请注意,有更好的方法可以将状态控制循环添加到您的 UI。例如,我在示例中使用了静态变量 - 您不应该在应用程序中这样做 - 除非确实有必要。
关于java - java testng 当条件达到时完成测试用例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34083699/