Java中whenpressed,如何在JAVA中触发一个KeyPressed事件进行单元测试

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

解决方案

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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值