2016-12-14 35 views
0

我有這樣的代碼在Java中:測試使用JUnit中的keyPressed

public class KeyboardListener implements KeyListener 
    { 
     public void keyPressed(final KeyEvent the_event) { 
      final int key = the_event.getKeyCode(); 

      if (key == KeyEvent.VK_UP && game.my_snake_direction != 40) 
      { 
       game.my_snake_direction = key; 
       game.moveSnake(KeyDirections.UP.getDirection()); 
      } 
     // ... 

而且我想測試鍵擊,但我不知道如何創建測試代碼的事件或組件。在我的代碼中,我沒有任何組件。我應該在測試代碼中創建一個組件嗎?

@Test 
    public void KeyPressTest() { 

    KeyboardListener KL = new KeyboardListener(); 
    KeyEvent the_event; //=new KeyEvent(..fail component..); 
    KL.KeyPressed(the_event); //here the_event isn't init 

PS:對不起,我的英語。

謝謝

回答

0

參考類Robot

添加到您的函數:

Robot robot = new Robot(); 
robot.keyPress(KeyEvent.VK_WHATEVER);