Data-driven tests with jUnit

后端 未结 10 593
囚心锁ツ
囚心锁ツ 2020-12-05 00:33

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, ..

相关标签:
10条回答
  • 2020-12-05 00:55

    I use combination of dbUnit, jMock and jUnit 4. Then you can ether run it as suite or separately

    0 讨论(0)
  • 2020-12-05 00:59

    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.

    0 讨论(0)
  • 2020-12-05 01:07

    You are better off extending TestCase with a DataDrivenTestCase that suits your needs.

    Here is working example: http://mrlalonde.blogspot.ca/2012/08/data-driven-tests-with-junit.html

    Unlike parameterized tests, it allows for nicely named test cases.

    0 讨论(0)
  • 2020-12-05 01:08

    We currently have a props file with our ID numbers in it. This is horribly brittle, but is easy to get something going. Our plan is to initially have these ID numbers overridable by -D properties in our ant builds.

    Our environment uses a legacy DB with horribly intertwined data that is not loadable before a run (e.g. by dbUnit). Eventually we would like to get to where a unit test would query the DB to find an ID with the property under test, then use that ID in the unit test. It would be slow and is more properly called integration testing, not "unit testing", but we would be testing against real data to avoid the situation where our app runs perfectly against test data but fails with real data.

    0 讨论(0)
  • 2020-12-05 01:08

    Some tests will lend themselves to being interface driven.

    If the database/file reads are retrieved by an interface call then simply get your unit test to implement the interface and the unit test class can return whatever data you want.

    0 讨论(0)
  • 2020-12-05 01:10

    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.

    0 讨论(0)
提交回复
热议问题