Data-driven tests with jUnit

ripper234 picture ripper234 · Nov 30, 2009 · Viewed 30.2k times · Source

What do you use for writing data-driven tests in jUnit?

(My definition of) a data-driven test is a test that reads data from some external source (file, database, ...), executes one test per line/file/whatever, and displays the results in a test runner as if you had separate tests - the result of each run is displayed separately, not in one huge aggregate.

Answer

matt picture matt · Nov 30, 2009

In JUnit4 you can use the Parameterized testrunner to do data driven tests.

It's not terribly well documented, but the basic idea is to create a static method (annotated with @Parameters) that returns a Collection of Object arrays. Each of these arrays are used as the arguments for the test class constructor, and then the usual test methods can be run using fields set in the constructor.

You can write code to read and parse an external text file in the @Parameters method (or get data from another external source), and then you'd be able to add new tests by editing this file without recompiling the tests.