如何在junit测试中模拟按键?

时间:2014-01-12 13:44:17

标签: java junit keypress awtrobot

我的主要课程Board(扩展JPanel):

 public class TAdapter extends KeyAdapter {

   public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();

        if ((key == KeyEvent.VK_LEFT) && (!right)) {
            left = true;
            up = false;
            down = false;
        }
  }

当我按左键时,我试图测试左边是否为真:

 @Test
 public void testKeyPressed() throws AWTException {
    Board instance = new Board();
    Robot rob = new Robot();
    instance.setFocusable(true);
    instance.requestFocus();
    rob.keyPress(KeyEvent.VK_LEFT);
    System.out.println(instance.up);
}

谢谢!

1 个答案:

答案 0 :(得分:3)

以下是一些可以实现此目的的代码:

KeyEvent key = new KeyEvent(instance, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0,  KeyEvent.VK_UP,'Z');
    instance.getKeyListeners()[0].keyPressed(key);