PeWu PeWu - 1 year ago 57
Java Question

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?

Answer Source

You could try testing for specific, known features of the output e.g.:

  • It there a white pixel at (100,100)?
  • It the border completely black?
  • Is the image the expected size?

And/or you could write tests for some "aggregate properties" that allow for some fuzziness in the results:

  • Does the image at least 90% match the reference image? (to allow for different fonts, antialiasing differences etc.)
  • Is the most common colour in the image equal to the background colour?