Slim_Shady
Slim_Shady

Reputation: 99

Junit testcase for a method with Graphics parameter

I' trying to make testcases in junit for my snake game. I have a gameover method and I'm trying to test it:

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

My main class is Board and it extends JPanel. The test:

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

I get a java.lang.NullPointerException when I try to run the gameOver method on instance. Please help!! I'm new at 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)

Upvotes: 0

Views: 1888

Answers (2)

isah
isah

Reputation: 5341

Without getting into details, you can provide a mock of Graphics object.

For example, using 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);
}

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

You're getting a Graphics instance by calling getGraphics() on a component, almost always a bad idea, since the Graphics object thus obtained is never long-lasting, and doing it before the component has been rendered, a horrific idea. So don't be surprised that it's null.

Solution: you should only work with Graphic objects passed into paintComponnt(Graphics g) method overrides, or if obtained from a BufferedImage, that's it.

Upvotes: 0

Related Questions