Is there a standard best-practice for unit testing code that generates graphics? I am working specifically with Java and jUnit, but I think the concept would apply in other languages as well.
So far, the best that I can come up with is using Mockito to mock the Graphics
object and assert pre-calculated things such as (pseudocode):
assert that graphics.drawString was called with ("abc", 50, 100)
assert that graphics.setBackgroundColor was called with Color.RED
While this is all well and good, I was wondering if this is the right way to go about it or if there are more established practices for testing graphical code.
I don't know if this is established practice, but I would consider an SVGGraphics2D from the Batik project for mocking Graphics, and comparing the generated SVG files.
The advantage over comparing binary files is that SVG files are relatively readable XML files, so if the two files are not equal, you not only know that there is a problem, but also you get a good hint about the exact place of the problem.
The advantage over your solution is that these SVG files can be viewed (for example in a browser), so the tested scenario is self-documented.
You could use something like Mockito, and mock your graphics object. Then you can verify that the methods drawString and setBackgroundColor were called. Taking some examples from here
Something like:
import static org.mockito.Mockito.*;
Graphics graphics= mock(Graphics.class);
//Run you code ....
//verification that the methods were called
verify(mockedList).drawString ("abc", 50, 100);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With