JUnit在Java中测试GUI [英] JUnit Tests for GUI in Java

查看:123
本文介绍了JUnit在Java中测试GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为GUI编写测试用例。我想知道你如何模拟JButton的点击,或者你如何提取JTable的元素。

I would like to write test cases for a GUI. I want to know how do you simulate a click of JButton, or how do you extract the elements of a JTable.

为了这个目的,我构建了一个简单的如果单击按钮且JTextfield为空,则将计数增加1的GUI,但如果提供了数字,则计数将替换为JTextfield中的整数。当然我想使用正则表达式来确保输入到JTextfield的文本实际上是一个整数,但我们假设用户不会乱七八糟并输入一个非整数。此外,JLabel在JTable添加新行时更新当前计数。

For the purpose of this, I have built a simple GUI that increase the count by 1 if the button is clicked and the JTextfield is empty, but the count is replaced by the integer in the JTextfield if a number is provided. Of course I would like to use Regex to make sure the text entered into the JTextfield is actually an integer, but let's assume users won't mess around and enter a non-integer. In addition, the JLabel updates the current count while the JTable adds a new row.

以下是代码:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;


public class sampleGUI extends JFrame implements ActionListener {
    private Integer previous_count;
    private Integer current_count;
    private JButton Button;
    private JTable table;
    private JTextField text;
    private DefaultTableModel model;
    private JScrollPane scroll;
    private JLabel label;

    public sampleGUI() {
        previous_count = null;
        current_count = 0;
        JFrame frame = new JFrame("Sample");
        JPanel panel = new JPanel();

        GroupLayout layout = new GroupLayout(panel);
        panel.setLayout(layout);

        label = new JLabel("Current Count: " + Integer.toString(current_count));
        text = new JTextField(15);
        Button = new JButton("Change the Count!");
        model = new DefaultTableModel();
        model.addColumn("Previous Count");
        model.addColumn("Current Count");
        table = new JTable(model);
        scroll = new JScrollPane(table);

        layout.setHorizontalGroup(layout
                .createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(
                        layout.createSequentialGroup().addComponent(label)
                                .addComponent(text).addComponent(Button))

                .addComponent(scroll));

        layout.setVerticalGroup(layout
                .createSequentialGroup()
                .addGroup(
                        layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE)
                                .addComponent(label).addComponent(text)
                                .addComponent(Button)).addComponent(scroll));
        Button.addActionListener(this);

        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == Button) {
            if (text.getText().equals("")) {
                previous_count = current_count;
                current_count++;
                label.setText("Current Count: "
                        + Integer.toString(current_count));
                model.addRow(new Object[] { current_count, previous_count });
            } else {
                previous_count = current_count;
                current_count = Integer.parseInt(text.getText());
                label.setText("Current Count: "
                        + Integer.toString(current_count));
                text.setText("");
                model.addRow(new Object[] { current_count, previous_count });
            }
            table.changeSelection(table.getRowCount() - 1, 0, false,
                    false);
        }
    }

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                sampleGUI gui = new sampleGUI();
            }
        });
    }
}

假设我想模拟打开GUI,然后单击按钮一次而不输入任何文本,然后输入1234并单击按钮,然后单击按钮而不输入任何文本,JTable应该有3列:{{1,0},{1234,1},{1235, 1234}}。我怎么能为此编写测试?谢谢!

Let's say I would like to simulate opening the GUI, then click the button once without entering any text, then enter 1234 and click the button, then click the button without entering any text, the JTable should have 3 columns: {{1,0}, {1234, 1}, {1235, 1234}}. How can I write the test for that? Thanks!

推荐答案

Java SE附带了一个标准工具,用于执行此操作,机器人类。我只是用它来为游戏编写机器人并通过套接字服务器/客户端对远程控制单独的计算机,但它实际上是为了自动化测试,所以它应该适合你。基本格式很简单:

Java SE comes with a standard tool for doing just this, the Robot class. I've only ever used it to write bots for games and to remotely control a separate computer via a socket server/client pair, but it was actually intended to automate testing, and so it should work for you. The basic format is simple:

Robot bot = new Robot();
bot.mouseMove(10,10);
bot.mousePress(InputEvent.BUTTON1_MASK);
//add time between press and release or the input event system may 
//not think it is a click
try{Thread.sleep(250);}catch(InterruptedException e){}
bot.mouseRelease(InputEvent.BUTTON1_MASK);

当然,您也可以使用适当的keyPress / keyRelease方法以类似的方式模拟键盘事件。我有时发现使用机器人类的screenCapture方法以及在屏幕上搜索图像并确定点击的位置是有用的。

Of course you can simulate keyboard events in a similiar way as well using the appropriate keyPress/keyRelease methods. I've sometimes found it useful to use the screenCapture method of the robot class as well to seach for images on the screen and determine where to click.

注意:这并不要求您正在测试的窗口是在awt / swing上构建的,但它确实要求您使用的java实现支持awt。

Note: this does not require that the windows you are testing are built on awt/swing, however it does require that the java implementaton you are using supports awt.

这篇关于JUnit在Java中测试GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆