2014-01-12 28 views
0

我想在我的蛇遊戲的junit中製作測試用例。 我有一個GAMEOVER方法,我想測試一下:具有圖形參數的方法的Junit測試用例

public void gameOver(Graphics g) { 
    String msg = "Game Over"; 
    final Font small = new Font("Helvetica", Font.BOLD, 14); 
    FontMetrics metr = this.getFontMetrics(small); 

    g.setColor(Color.white); 
    g.setFont(small); 
    g.drawString(msg, (WIDTH - metr.stringWidth(msg))/2, 
       HEIGHT/2); 
    } 

我的主類是董事會和它擴展JPanel。測試:

public void testGameOver() { 
    System.out.println("gameOver"); 
    Board instance = new Board(); 
    Graphics g = instance.getGraphics(); 
    instance.gameOver(g); 
    Color tmp = new Color(instance.getBackground().getRGB()); 
    assertEquals(tmp,Color.white.getRGB()); 
    assertEquals(instance.getFont().getFontName(),new Font("Helvetica", Font.BOLD, 14).getFontName()); 
    } 

當我嘗試在實例上運行gameOver方法時,我得到一個java.lang.NullPointerException。請幫忙!!我是Junit的新手。

Testcase: testGameOver(snake.BoardTest): Caused an ERROR 
null 
java.lang.NullPointerException 
at snake.Board.gameOver(Board.java:121) 
at snake.BoardTest.testGameOver(BoardTest.java:67) 
+0

請發佈包含java.lang.NullPointerException的錯誤堆棧跟蹤。 – Scott

回答

1

沒有深入細節,您可以提供Graphics對象的mock對象。例如,使用Mockito

@Test 
public void shouldUpdateGraphicsToGameOver(){ 
    Graphics gMock = Mockito.mock(Graphics.class); 
    //expectations 
    Color expectedColor = Color.white; 
    Font expectedFont= ...; 
    String expectedMsg = ...; 
    int expectedWidth = ...; 
    int expectedHeight = ...; 

    classUnderTest.gameOver(gMock); 

    Mockito.verify(gMock).setColor(expectedColor); 
    Mockito.verify(gMock).setFont(expectedFont); 
    Mocktio.verify(gMock).drawString(expectedMsg, expectedWidth, expectedHeight); 
} 
+0

它的工作原理。非常感謝你!! –

0

你被一個組件上調用getGraphics(),幾乎總是一個壞主意得到一個Graphics實例,因爲對象所獲得的圖形是永遠不會持久,並之前做組件已呈現,一個可怕的想法。所以不要驚訝,它是空的。

解決方案:您應該只處理傳遞給paintComponnt(Graphics g)方法重寫的圖形對象,或者如果從BufferedImage獲得,就是這樣。

+0

對不起,我不明白爲了運行gameOver方法,我必須首先有一個g值。請解釋。我從來沒有使用過paintComponent。如果我只是重寫paint,那麼如何? –

+1

如果你想這樣做,而不是讓一個模擬的圖形對象作爲接受的答案建議,我會做它使用BufferedImage,其createGraphics()方法總是返回一個有效的圖形對象。 – Jules