How to trigger a KeyPressed event for unit testing in JAVA

限于喜欢 提交于 2019-12-24 03:07:46

问题


Ok, so I'm trying to Unit test some GUI elements I have a JButton with text of "Create" and the mnemonic set on 'C' or code 67. I can write a unit test that I can call the .doClick function on and assert that what that button is supposed to do, happens.

However, I now want to write a unit test to test that the mnemonic portion of that same button works identically to the button click. I've searched on and off for a couple of days now and have tried many things.

I've tried using Robot from the awt library:

robot.keyPress(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_C);

To which no event is being triggered and most recently I've tried this EventQueue example:

final Toolkit toolkit = Toolkit.getDefaultToolkit();
final EventQueue eventQueue = toolkit.getSystemEventQueue();
gPane = new SwingBuilder();
panel = new MainMenuPanel();
panel.displayMainMenu(gPane); 

@Test
void ShouldMakeRaceGenderPanelVisibleKeyPress(){
eventQueue.postEvent( new KeyEvent(panel.gPane.mainM, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, KeyEvent.VK_C ).getKeyCode());

    assertThat panel.gPane.mainM.isVisible(), is(false);
    assertThat panel.gPane.raceGender.isVisible(), is(true);
}

I know that GUI testing can be tricky and there are tools out there to simulate user interaction, but is it really that hard to simulate or trigger just a single KeyEvent?

Any assistance is welcome, and any UI testing tools recommended is welcome as well.

Thanks

Note: This is a combination of Java and Groovy, so I'm using SwingBuilder to build my UI's


回答1:


You state:

I have a JButton with text of "Create" and the mnemonic set on 'C' or code 67. ...
However, I now want to write a unit test to test that the mnemonic portion of that same button works identically to the button click. ...

I've tried using Robot from the awt library:

robot.keyPress(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_C);

Perhaps the problem is due to your not taking into account that JButton mnemonics are alt-key combinations, and so your robot code would probably have to reflect this:

robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_C);

// possibly want a small Thread.sleep(...) here?

robot.keyRelease(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_ALT);


来源:https://stackoverflow.com/questions/12998448/how-to-trigger-a-keypressed-event-for-unit-testing-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!