Skip to main content

Data-driven unit testing in Java

Posted by johnsmart on July 23, 2014 at 10:09 PM PDT

Data-driven testing is a powerful way of testing a given scenario with different combinations of values. In this article, we look at several ways to do data-driven unit testing in JUnit.

Suppose, for example, you are implementing a Frequent Flyer application that awards status levels (Bronze, Silver, Gold, Platinum) based on the number of status points you earn. The number of points needed for each level is shown here:

level

minimum status points

result level

Bronze

0

Bronze

Bronze

300

Silver

Bronze

700

Gold

Bronze

1500

Platinum

Our unit tests need to check that we can correctly calculate the status level achieved when a frequent flyer earns a certain number of points. This is a classic problem where data-driven tests would provide an elegant, efficient solution.

Data-driven testing is well-supported in modern JVM unit testing libraries such as Spock and Spec2. However, some teams don