gpt4 book ai didi

java - 在 JUnit 测试中模拟按键

转载 作者:行者123 更新时间:2023-11-30 10:22:40 25 4
gpt4 key购买 nike

我完全陷入了java测试;它是关于通过测试方法将字符“a”发送到 JFrame 组件的 JTextField。

JFrame 类实现了 KeyListener 接口(interface),因此重写了 KeyPressed、KeyTyped 和 KeyReleased。与此同时,我将 JTextField 的所有按键转移到 JFrame;在 JFrame 构造函数中,我有:

JTextField txf_version = new JTextField();
txf_version.addKeyListener(this);

我想测试这个行为,然后模拟在 JTextField 中键入一个字符的 Action 。

我所有的尝试都失败了;我尝试使用 java.awt.Robot 类,如下所示:hava a look at this other post in stack overflow ,但我有一个奇怪的行为:调用

robot.keyPress(KeyEvent.VK_A);

直接在我的IDE中显示字符,而不是在虚拟JFrame中!尝试使用 requestFocus() 或 requestFocusInWindow() 无效。

我还尝试了 KeyEvents:

KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_PRESSED, System
.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
bookWindow.txf_version.dispatchEvent(key);

但是文本域的文本属性没有改变...

这是我目前的方法:

@Test
void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
InterruptedException, NoSuchFieldException, IllegalAccessException {
initTest();

KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_PRESSED, System
.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
bookWindow.txf_version.dispatchEvent(key);

System.out.println("dans txf_version : " + bookWindow.txf_version.getText
());

assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());


}

我可以通过在 JFrame 的子类中编写一个 main() 方法来查看实际行为,但我认为了解如何模拟 swing 组件测试的键很有用。

谢谢

编辑:我根据 AJNeufeld 的回答更改了我的测试代码,但它仍然不起作用。这是我的测试代码:

@Test
void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
InterruptedException, NoSuchFieldException, IllegalAccessException,
InvocationTargetException {
//bookEditor2 & bookWindow
SwingUtilities.invokeAndWait(() -> {
bookWindow = new BookWindow();
VectorPerso two = new VectorPerso();
two.add(le_livre_de_la_jungle);
two.add(elogeMaths);
bookWindow.setTableDatas(two);
bookWindow.table.setRowSelectionInterval(1, 1);
bookWindow.txf_version.requestFocusInWindow();
KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_TYPED, System
.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
bookWindow.txf_version.dispatchEvent(key);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("dans txf_version : " + bookWindow.txf_version.getText
());

assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());
});


}

plintln 行在控制台中生成文本:“dans txf_version : 0”,表示 key 未发送到 txf_version。

编辑 2:

新尝试:

@Test
void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
InterruptedException, NoSuchFieldException, IllegalAccessException,
InvocationTargetException {
//bookEditor2 & bookWindow
SwingUtilities.invokeAndWait(() -> {
bookWindow = new BookWindow();
VectorPerso two = new VectorPerso();
two.add(le_livre_de_la_jungle);
two.add(elogeMaths);
bookWindow.setTableDatas(two);
bookWindow.table.setRowSelectionInterval(1, 1);
bookWindow.txf_version.requestFocusInWindow();
KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_TYPED, System

.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
bookWindow.txf_version.dispatchEvent(key);
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

SwingUtilities.invokeAndWait(() -> {
System.out.println("dans txf_version : " + bookWindow.txf_version.getText
());

assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());
});


}

最佳答案

我认为你做错了几件事,但没有完整的例子,很难说。

首先,JTextField 并不真正关心KEY_PRESSED 事件。它与 KEY_TYPED 事件有关。

其次,Swing 在事件调度线程 (EDT) 上处理事件,这不一定是 JUnit 将在其上运行的线程。当你不在 EDT 时,你真的不应该改变事情。我不确定 eventDispatch() 是否切换到 EDT。它可能。但它也可能使用 invokeLater() 执行此操作,在这种情况下,执行会立即传递给 assertEquals(),但会失败,因为事件处理尚未发生.

这是一个最小的、完整的、可验证的例子,它显示了一个发送的按键,它改变了按钮的颜色,以及一个检查它并通过的 JUnit 测试用例:

首先是被测代码:

public class SwingUnitTesting extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(SwingUnitTesting::new);
}

JTextField tf = new JTextField();
JButton btn = new JButton("Test Button");

SwingUnitTesting() {
add(tf, BorderLayout.PAGE_END);
add(btn, BorderLayout.PAGE_START);

tf.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
btn.setForeground(Color.RED);
}
});

setSize(200, 80);
setLocationByPlatform(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
}
}

单元测试:

public class SwingUnitTestingTest {

SwingUnitTesting sut;

@Before
public void setUp() throws Exception {
SwingUtilities.invokeAndWait(() -> {
sut = new SwingUnitTesting();
});
}

@Test
public void btnNotRedBeforeKeypress() throws InvocationTargetException, InterruptedException {
SwingUtilities.invokeAndWait(() -> {
assertNotEquals(Color.RED, sut.btn.getForeground());
});
}

@Test
public void btnRedAfterKeypress() throws InvocationTargetException, InterruptedException {
SwingUtilities.invokeAndWait(() -> {
sut.tf.requestFocusInWindow();
sut.tf.dispatchEvent(new KeyEvent(sut.tf,
KeyEvent.KEY_TYPED, System.currentTimeMillis(), 0,
KeyEvent.VK_UNDEFINED, 'A'));
assertEquals(Color.RED, sut.btn.getForeground());
});
}
}

您可能可以使用一些 JUnit @Rule 技巧或自定义运行器在运行 Swing 测试时自动更改为 EDT。


更新:

我很好奇,并试图找到一个现有的 @Rule,它将 @Before@Test@在 代码进入 EDT 之后,但我的 Google-fu 失败了;我知道我以前见过它,但我找不到了。最后,我创建了自己的:

public class EDTRule implements TestRule {

@Override
public Statement apply(Statement stmt, Description dscr) {
return new Statement() {
private Throwable ex;

@Override
public void evaluate() throws Throwable {
SwingUtilities.invokeAndWait(() -> {
try {
stmt.evaluate();
} catch (Throwable t) {
ex = t;
}
});
if (ex != null) {
throw ex;
}
}
};
}
}

使用这个规则,JUnit 测试变得更简单一些:

public class SwingUnitTestingTest {

@Rule
public TestRule edt = new EDTRule();

SwingUnitTesting sut;

@Before
public void setUp() throws Exception {
sut = new SwingUnitTesting();
}

@Test
public void btnNotRedBeforeKeypress() {
assertNotEquals(Color.RED, sut.btn.getForeground());
}

@Test
public void btnRedAfterKeypress() {
sut.tf.requestFocusInWindow();
sut.tf.dispatchEvent(
new KeyEvent(sut.tf, KeyEvent.KEY_TYPED, System.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'A'));
assertEquals(Color.RED, sut.btn.getForeground());
}
}

在 MacOS 上测试,使用 jdk1.8.0_121

关于java - 在 JUnit 测试中模拟按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47336703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com