Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Test Graphics

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.

like image 997
Mike Clark Avatar asked Feb 19 '13 15:02

Mike Clark


2 Answers

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.

like image 56
lbalazscs Avatar answered Sep 27 '22 22:09

lbalazscs


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);
like image 28
Andres Olarte Avatar answered Sep 28 '22 00:09

Andres Olarte