Java - 验证空字段

时间:2014-04-19 18:02:46

标签: java swing junit

我正在尝试验证是否需要特定字段(isbnTextField)。我想确保首先编写一个测试,以遵循敏捷开发的原则。但是,我在测试testThatBookNumberIsRequired中收到空指针异常。为什么找不到这个textField?

修改:

public class BookOrderingGUI extends JFrame {

    private JTextField isbnTextField;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    BookOrderingGUI window = new BookOrderingGUI();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */

    public BookOrderingGUI() {
        initialize();
    }

    public void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 600, 450);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        tabbedPane.setBounds(0, 0, 584, 412);
        frame.getContentPane().add(tabbedPane);

        JPanel panelOrders = new JPanel();
        tabbedPane.addTab("Orders", null, panelOrders, null);
        panelOrders.setLayout(null);

        isbnTextField = new JTextField();
        isbnTextField.setBounds(80, 8, 86, 20);
        panelOrders.add(isbnTextField);
        isbnTextField.setColumns(10);
    }
}

测试

public class TestBookOrdering extends TestCase {
    private BookOrderingGUI window;

    @Before
    public void setUp() {
        this.window = new BookOrderingGUI();
        this.window.setVisible(true);
    }

    @Test
    public void testThatBookNumberIsRequired() {
        JTextField target = (JTextField) this.window.getComponentAt(80, 8);
        target.setText(null);
        target.postActionEvent();
        assertFalse(target.getText().isEmpty());
    }
}

1 个答案:

答案 0 :(得分:0)

对于任何有兴趣的人,我最终都会编写一个getter方法来定位特定的字段和按钮。由于该操作与此按钮绑定,然后我使用doClick()模拟用户点击。我还制作了一个初始标志,以确定该字段何时变为无效的状态。结果如下:

@Test
public void testThatBookNumberIsRequired() {
    targetField = this.window.getBookNumber();
    targetButton = this.window.getSubmit();

    targetField.setText(null);
    targetButton.doClick();

    assertFalse(this.window.isValid);
}