简体   繁体   中英

Simulate a mouse click during test. JUnit, JavaFX

In my test method, I'm trying to simulate a mouse click using Robot class:

@Test
public void testMouseEvents(){
    clickMouse();
}

private void clickMouse() {
    final boolean[] flag = {true};
    Platform.runLater(() -> {
        try {
            Robot robot = new Robot();
            robot.mouseMove(900, 500);
            robot.delay(2000);
            robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            robot.delay(2000);
            robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
            robot.delay(2000);
        } catch (Exception ignored) {

        }
        flag[0] = false;
    });

    try {
        while (flag[0]) {
            Thread.sleep(3);
        }
        Thread.sleep(20);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

But the last method throws different exeptions: sometimes it's NullPointerm but more often it's:

java.util.concurrent.RejectedExecutionException: Task     com.sun.javafx.tk.quantum.PaintRenderJob@24f7eafc rejected from  com.sun.javafx.tk.quantum.QuantumRenderer@14a5ef25[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 4]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)

Curiously, but when I simulate KeyEvent, it works perfectly. Moreover, if I delete the line where the mouse key is supposed to be pressed, the robot moves the cursor and no exception is thrown. I suspect that the issue might concern the thread in which JavaFX application works. But still I can't figure out why it doesn't work.

mimicking an actual mouse click on a Button is (I think) considerd to be a no-no (yes I have seen "developers" solving issues this way in non-JUnit issues)

The best thing to do is to de-couple the button push evenet and its action: rewrite the button click so that it will invoke a certain class which allow you to invoke that exact same code from JUnit itself. There will be a different way of plumbing the same code in the real application and in the test harnass: the command invoked will be the same which is the aim of your exercise. It will also get rid of that strange nasty exception you get which is something you can expect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM