我不是在寻找一个 GUI 测试工具来做这个,我想从
我自己的 java 应用程序。
TLDR:检查 assertj-swing 的来源,然后再决定是否需要自己编写。
我想请您耐心等待,因为我仍然会参考现有的测试工具来开始回答。 assertj-swing(FEST 的分支)在其入门指南中展示了以下示例。
public class SimpleCopyApplicationTest {
private FrameFixture window;
@BeforeClass
public static void setUpOnce() {
FailOnThreadViolationRepaintManager.install();
}
@Before
public void setUp() {
SimpleCopyApplication frame = GuiActionRunner.execute(() -> new SimpleCopyApplication());
window = new FrameFixture(frame);
window.show(); // shows the frame to test
}
@Test
public void shouldCopyTextInLabelWhenClickingButton() {
window.textBox("textToCopy").enterText("Some random text");
window.button("copyButton").click();
window.label("copiedText").requireText("Some random text");
}
@After
public void tearDown() {
window.cleanUp();
}
}
见:http://joel-costigliola.github.io/assertj/assertj-swing-getting-started.html
此示例不同于浏览器自动化测试(例如使用 Selenium)通常的工作方式。它不是针对您的应用程序的真实实例运行测试,而是将您的应用程序 GUI 容器(更高或更低级别)像 JFrame 一样包装在另一个名为 Fixture 的对象中。然后将针对此 Fixture 对象的实例执行检查。
这是否意味着无法运行整个应用程序?没有。
如果你花一些时间在 assertj-swing 的 github 存储库中,它有一个名为 ApplicationLauncher.java 的类,它允许你实例化一个具有 main 方法的类。
从具有“main”方法的类中执行 Java 应用程序。
https://github.com/joel-costigliola/assertj-swing/blob/master/assertj-swing/src/main/java/org/assertj/swing/launcher/ApplicationLauncher.java
让我们记住 Sergiy 提到的 java.awt.Robot 在这里非常重要。
该类用于为
测试自动化、自运行演示和其他目的
需要控制鼠标和键盘的应用程序。这
Robot的主要目的是促进Java的自动化测试
平台实现。
使用类生成输入事件与发布事件不同
到 AWT 事件队列或 AWT 组件,因为事件是
在平台的本机输入队列中生成。例如,
Robot.mouseMove 实际上会移动鼠标光标,而不仅仅是
生成鼠标移动事件。
来源:https://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html
我们现在可以看到另一个例子:
ApplicationLauncher.application(app.qahelp.core.app.Runner.class)
.withArgs(arg).start();
...
robot = BasicRobot.robotWithCurrentAwtHierarchy();
// Find main frame of application
FrameFixture frame = WindowFinder.findFrame(
getMainFrameByName("Celsius")).using(robot);
frame.focus();
// Type 120 in text box
frame.textBox("tempCelsius").setText("120");
...
frame.button("convertTemp").click();
...
// Get result conversion
JLabelFixture lableResult = frame
.label(getLableTextByTextContain("Fahrenheit"));
AssertJUnit.assertTrue(lableResult.text().contains("248"));
...
来源:http://helpqaspb.com/swing.htm
我的回答的重点是,我相信您应该学习使用源代码附带的现有工具之一。然后,如果您了解它的工作原理,请确保您确实需要自己的工具,或者您可以为现有的工具做出贡献。