如何通过 JUnit 测试正确触发 KeyListener

问题描述

我有一个将 KeyListener 添加到组合框的方法

public static void setListener(final JComboBox comboBox) {
        JTextField textField = (JTextField) comboBox.getEditor().getEditorComponent();
        textField.addKeyListener(new KeyAdapter() {
            
            @Override
            public void keypressed(final KeyEvent ke) {
                SwingUtilities.invokelater(new Runnable() { 
                //Bunch of Stuff
                });
            }
        });     

一切都在运行环境中工作。它基本上只是通过其 textField 中的输入来过滤组合框中的项目。

(如果我输入“B”,那么组合框内剩下的唯一项目将以“B”开头的项目)

问题是,我无法在单元测试中触发 setListener() 方法keyreleased() 方法

我已经尝试了以下

public void testListFilter(){
final JComboBox<String> comboBox = new JComboBox();
comboBox.setEditable(true);
//...filling it with test items...
comboBox.setFocusable(true);
comboBox.requestFocusInWindow();

differentClass.setListener(comboBox);

KeyEvent key = new KeyEvent(comboBox,KeyEvent.KEY_pressed,System.currentTimeMillis(),KeyEvent.VK_B,'B');
comboBox.getKeyListeners()[0].keypressed(key);

int number = comboBox.getSelectedindex();//returns a 3,which is the position of the next item starting with "B"; 
//Showing that the Keystroke is succesfully registered inside the comboBox

ArrayList<String> comboBoxContent = new ArrayList<>();
for (int j = 0; j <= comboBox.getItemCount() - 1; j++) {
        comboBoxContent.add(comboBox.getItemAt(j));
}

assertthat("",comboBoxContent,contains("BIC","BID"));
assertthat("",not(contains("HIJ","KLM","nop")));

}

虽然 keystroke 是在 testListFilter 方法注册的,但在 ComboBox 中。它不会触发 setListener() 方法中的 keyreleased() 方法。有谁知道我该如何解决这个问题?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)