2014-01-12 58 views
1

我有這個在我的主類Board(擴展JPanel):如何在junit測試中模擬按鍵?

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

謝謝!

+0

它看起來對我來說,那類'擴展KeyAdapter'。 –

+1

Board擴展Jpanel; TAdapter擴展了KeyAdapter; TAdapter是在Board類中定義的。 –

+0

'rob.keyPress(...)'如何連接到'TAdapter'的'keyPressed(...)'方法?但是,您可以直接在單元測試中調用'instance.getTAdapter()。keyPressed(...)'(如果有類似'getTAdapter()')的內容並驗證結果。 –

回答

3

下面是一些代碼,可以實現這一目標:

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

有用...但只有組件具有KeyListeners時纔有用。另一種機制是InputMap(s)-ActionMap。爲此,您需要創建KeyStrokes,獲取IM值(String),然後獲取AM值(Action)...然後執行action.actionPerformed()。根據我的經驗,actionPerformed()並不總是像你希望的那樣工作...... –