启动这样的(或等效的)Java 程序时:
Runtime.getRuntime().exec("java -jar someJar.jar")
是否可以获得对已启动程序的 JFrame 的引用,以便可以使用FEST之类的库(例如在测试中)实现自动化?
当程序在同一个虚拟机中启动时,很容易做到这一点,如下面的例子所示,但由于几个原因,我不能这样做。该程序必须与启动它的虚拟机/进程分开,如上所述或类似。但是,当使用上面的代码启动进程时,下面的 FEST 代码没有找到框架。
使用 FEST 和来自Java Reflection 的改编代码的示例。运行一个外部 jar 并引用它的类?:(FrameFixture
只是 a 的自动化包装器JFrame
):
Thread t = new Thread(new Runnable() {
public void run() {
File file = new File("someJar.jar");
URLClassLoader cl;
try {
cl = new URLClassLoader( new URL[]{file.toURI().toURL()} );
}
catch (MalformedURLException e) {}
Class<?> clazz = null;
try {
clazz = cl.loadClass("Main");
}
catch (ClassNotFoundException e) {}
Method main = null;
try {
main = clazz.getMethod("main", String[].class);
}
catch (NoSuchMethodException e) {}
try {
main.invoke(null, new Object[]{new String[]{}});
}
catch (Exception e) {}
}
});
t.start();
GenericTypeMatcher<JFrame> matcher = new GenericTypeMatcher<JFrame>(JFrame.class) {
protected boolean isMatching(JFrame frame) {
return "TestFrame".equals(frame.getTitle()) && frame.isShowing();
}
};
FrameFixture frame = WindowFinder.findFrame(matcher).using(BasicRobot.robotWithCurrentAwtHierarchy());
frame.maximize();