JUnit and JFileChoosers

I am having problems with some test cases that use JFileChoosers. I am looking for a way to programmatically get rid of file selection windows (instead of pressing ESC 7 times) when running JUnit tests.

I tried to include the following in my test case:

Robot robot = new Robot();
robot.delay(1000);
robot.keyPress(KeyEvent.VK_ESCAPE);

This does not work. Do you have any suggestions?

Thanks in advance.

+3
source share
1 answer

Just guess, but it looks like you are using Robotin the same thread as when starting up JFileChooser. If memory is used, many JFileChooser methods block the current thread until the user selects a file.

Try running Robotin a separate thread if you haven't already.

EDIT:

For instance:

// Start Robot in a new thread.
new Thread(new Runnable() {
    @Override
    public void run() {
        Robot robot = new Robot();
        robot.delay(1000);
        robot.keyPress(KeyEvent.VK_ESCAPE);
    }
}).start();

// Launch JFileChooser.
jFileChooser.getSelectedFile();
+2
source

All Articles