如何解决如何通过 JUnit 测试正确触发 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 举报,一经查实,本站将立刻删除。