Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data-driven tests with jUnit

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.

like image 314
ripper234 Avatar asked Nov 30 '09 20:11

ripper234


People also ask

Is JUnit used for TDD?

JUnit is a unit testing framework designed for Java programming language. Since unit tests are the smallest elements in the test automation process. With the help of unit tests, we can check the business logic of any class. So JUnit plays an important role in the development of a test-driven development framework.

Does JUnit have data provider?

Apparently JUnit does not provide support for data providers, which makes it rather annoying to test the same method with 20 different versions of an argument.

Can JUnit be used for API testing?

Unit testing APIs is an important part of API testing. Unit testing ensures that API components will function properly. In this article we will learn how to cover JUnit REST API testing with Spring Boot.


2 Answers

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.

like image 174
matt Avatar answered Oct 14 '22 16:10

matt


This is where TestNG, with its @DataSource, shines. That's one reason why I prefer it to JUnit. The others are dependencies and parallel threaded tests.

like image 32
duffymo Avatar answered Oct 14 '22 15:10

duffymo