Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing graphics generation with JUnit

I'm using Java's Graphics2D to generate a graphical representation of a graph. I'm also using ImageIO to write a PNG file. (ImageIO.write(image, "png", out);)

I'm wondering how should I write JUnit tests to test whether the generated graphics is what is expected. I could pre-generate the PNG files but what if the font is a bit different on a different machine?

like image 611
PeWu Avatar asked Aug 03 '10 20:08

PeWu


1 Answers

For me, this concrete implementation seems to work:

private void compareRasterImages(BufferedImage expectedPngIo, BufferedImage actualPngIo) throws AssertionError {
    int minX = expectedPngIo.getMinX();
    int minY = expectedPngIo.getMinY();
    int maxX = expectedPngIo.getMinX() + expectedPngIo.getWidth();
    int maxY = expectedPngIo.getMinY()+ expectedPngIo.getHeight();

    assertEquals(minX, actualPngIo.getMinX()); 
    assertEquals(minY, actualPngIo.getMinY()); 
    assertEquals(expectedPngIo.getHeight(), actualPngIo.getHeight()); 
    assertEquals(expectedPngIo.getWidth(), actualPngIo.getWidth()); 
    for (int x_i = minX; x_i < maxX; x_i++){
        for (int y_i = minY; y_i < maxY; y_i++) {
            assertEquals(expectedPngIo.getRGB(x_i, y_i), actualPngIo.getRGB(x_i, y_i));
        }
    }
}

I retrieve the BufferedImage from my PNG (as byte[]) using ImageIO:

BufferedImage expectedPngIo = ImageIO.read(new ByteArrayInputStream(expectedPng));
enter code here
like image 109
RobertG Avatar answered Sep 17 '22 13:09

RobertG