Mike Clark
Mike Clark

Reputation: 11979

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.

Upvotes: 6

Views: 2545

Answers (3)

piotrek
piotrek

Reputation: 14550

as you mentioned, you can test your calculations and calling graphics api. that's easy. but checking if you are using the graphics api correctly (and produce the correct picture), can be really difficult. i know some companies make screenshots of the generated graphics (e.g. web page) and compare it with expected result using many complex metrics. but usually it's not a way to reduce cost but some manager's yearly goal (let's say 'process automation'). so think twice before you go this way - usually it's not worth the pain

Upvotes: 2

Andres Olarte
Andres Olarte

Reputation: 4380

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

Upvotes: 2

lbalazscs
lbalazscs

Reputation: 17784

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.

Upvotes: 4

Related Questions