Data-driven Unit Testing in Java
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’t have the option of using a language other than Java, or are limited to using JUnit. In this article, we look at a few options for data-driven testing in plain old JUnit. Parameterized Tests in JUnit JUnit provides some support for data-driven tests, via the Parameterized test runner. A simple data-driven test in JUnit using this approach might look like this: @RunWith(Parameterized.class) public class WhenEarningStatus { @Parameters(name = "{index}: {0} initially had {1} points, earns {2} points, should become {3} ") public static Iterable data() { return Arrays.asList(new Object[][]{ {Bronze, 0, 100, Bronze}, {Bronze, 0, 300, Silver}, {Bronze, 100, 200, Silver}, {Bronze, 0, 700, Gold}, {Bronze, 0, 1500, Platinum}, }); } private Status initialStatus; private int initialPoints; private int earnedPoints; private Status finalStatus; public WhenEarningStatus(Status initialStatus, int initialPoints, int earnedPoints, Status finalStatus) { this.initialStatus = initialStatus; this.initialPoints = initialPoints; this.earnedPoints = earnedPoints; this.finalStatus = finalStatus; } @Test public void shouldUpgradeStatusBasedOnPointsEarned() { FrequentFlyer member = FrequentFlyer.withFrequentFlyerNumber("12345678") .named("Joe", "Jones") .withStatusPoints(initialPoints) .withStatus(initialStatus); member.earns(earnedPoints).statusPoints(); assertThat(member.getStatus()).isEqualTo(finalStatus); } } You provide the test data in the form of a list of Object arrays, identified by the _@Parameterized@ annotation. These object arrays contain the rows of test data that you use for your data-driven test. Each row is used to instantiate member variables of the class, via the constructor. When you run the test, JUnit will instantiate and run a test for each row of data. You can use the name attribute of the @Parameterized annotation to provide a more meaningful title for each test. There are a few limitations to the JUnit parameterized tests. The most important is that, since the test data is defined at a class level and not at a test level, you can only have one set of test data per test class. Not to mention that the code is somewhat cluttered - you need to define member variables, a constructor, and so forth. Fortunatly, there is a better option. Using JUnitParams A more elegant way to do data-driven testing in JUnit is to use [https://code.google.com/p/junitparams/|JUnitParams]. JUnitParams (see [http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22JUnitParams%22|Maven Central] to find the latest version) is an open source library that makes data-driven testing in JUnit easier and more explicit. A simple data-driven test using JUnitParam looks like this: @RunWith(JUnitParamsRunner.class) public class WhenEarningStatusWithJUnitParams { @Test @Parameters({ "Bronze, 0, 100, Bronze", "Bronze, 0, 300, Silver", "Bronze, 100, 200, Silver", "Bronze, 0, 700, Gold", "Bronze, 0, 1500, Platinum" }) public void shouldUpgradeStatusBasedOnPointsEarned(Status initialStatus, int initialPoints, int earnedPoints, Status finalStatus) { FrequentFlyer member = FrequentFlyer.withFrequentFlyerNumber("12345678") .named("Joe", "Jones") .withStatusPoints(initialPoints) .withStatus(initialStatus); member.earns(earnedPoints).statusPoints(); assertThat(member.getStatus()).isEqualTo(finalStatus); } } Test data is defined in the @Parameters annotation, which is associated with the test itself, not the class, and passed to the test via method parameters. This makes it possible to have different sets of test data for different tests in the same class, or mixing data-driven tests with normal tests in the same class, which is a much more logical way of organizing your classes. JUnitParam also lets you get test data from other methods, as illustrated here: @Test @Parameters(method = "sampleData") public void shouldUpgradeStatusFromEarnedPoints(Status initialStatus, int initialPoints, int earnedPoints, Status finalStatus) { FrequentFlyer member = FrequentFlyer.withFrequentFlyerNumber("12345678") .named("Joe", "Jones") .withStatusPoints(initialPoints) .withStatus(initialStatus); member.earns(earnedPoints).statusPoints(); assertThat(member.getStatus()).isEqualTo(finalStatus); } private Object[] sampleData() { return $( $(Bronze, 0, 100, Bronze), $(Bronze, 0, 300, Silver), $(Bronze, 100, 200, Silver) ); } The $ method provides a convenient short-hand to convert test data to the Object arrays that need to be returned. You can also externalize @Test @Parameters(source=StatusTestData.class) public void shouldUpgradeStatusFromEarnedPoints(Status initialStatus,int initialPoints, int earnedPoints,Status finalStatus){ ... } The test data here comes from a method in the StatusTestData class: public class StatusTestData{ public static Object[] provideEarnedPointsTable(){ return $( $(Bronze,0, 100,Bronze), $(Bronze,0, 300,Silver), $(Bronze,100,200,Silver) ); } } This method needs to be static, return an object array, and start with the word "provide". Getting test data from external methods or classes in this way opens the way to retrieving test data from external sources such as CSV or Excel files. JUnitParam provides a simple and clean way to implement data-driven tests in JUnit, without the overhead and limitations of the traditional JUnit parameterized tests. Testing with non-Java languages If you are not constrained to Java and/or JUnit, more modern tools such as Spock (https://code.google.com/p/spock/) and Spec2 provide great ways of writing clean, expressive unit tests in Groovy and Scala respectively. In Groovy, for example, you could write a test like the following: class WhenEarningStatus extends Specification{ def"should earn status based on the number of points earned"(){ given: def member =FrequentFlyer.withFrequentFlyerNumber("12345678") .named("Joe","Jones") .withStatusPoints(initialPoints) .withStatus(initialStatus); when: member.earns(earnedPoints).statusPoints() then: member.status == finalStatus where: initialStatus | initialPoints | earnedPoints | finalStatus Bronze |0 |100 |Bronze Bronze |0 |300 |Silver Bronze |100 |200 |Silver Silver |0 |700 |Gold Gold |0 |1500 |Platinum } } John Ferguson Smart is a specialist in BDD, automated testing, and software life cycle development optimization, and author of BDD in Action and other books. John runsregular courses in Australia, London and Europe on related topics such as Agile Requirements Gathering, Behaviour Driven Development, Test Driven Development, andAutomated Acceptance Testing. Blog Links >>
July 27, 2014
·
23,971 Views
·
1 Like
Comments
Aug 22, 2014 · Mr B Loid
I've seem teams over-invest in unit tests, but usually when they think of them as tests, which in my opinion is not an effective way of working. And I absolutely agree, tests can be badly written, in which case they loose a lot of their value.
For these reasons, I prefer to think in terms of executable specifications, starting from high level, often end-to-end automated acceptance criteria (which play the role of integration tests), and working down to more detailed specifications for low level components. Whether it is implemented as a unit or an integration test is not that important to me, unless it adversely affects the time it takes to run (and hence the feedback cycle). The quality of the tests, and just as importantly, their relevance, is built in: if I don't know what a unit test does, I consider that I might as well delete it because if it fails, I won't know what to do. So the way the tests are named, how they are organized, and how they are written, is critical. Tests written this way are good at finding regressions, but they also document your thought process when you wrote them.
Written this way, these tests most definitely do help me sleep better ;-).
Aug 21, 2014 · Mr B Loid
The key word here is "knowingly": the habit I am referring to here is when developers knowingly commit code that will break the build, because some of the acceptance tests are still "work-in-progress".
Oct 17, 2012 · admin
Oct 17, 2012 · James Sugrue
Jul 23, 2011 · Dev Stonez
Jul 19, 2011 · Lebon Bon Lebon
Jul 17, 2011 · Lebon Bon Lebon
Mar 13, 2011 · Gerd Storm
Mar 13, 2011 · Gerd Storm
Mar 13, 2011 · Gerd Storm
Aug 20, 2010 · Andrea Ingaglio
May 12, 2010 · Tony Thomas
Jan 03, 2010 · Joseph Bradington
Jan 03, 2010 · Joseph Bradington
Nov 25, 2009 · Alex Miller
Oct 21, 2009 · Mr B Loid
Oct 15, 2009 · Mr B Loid
Oct 15, 2009 · Mr B Loid
Oct 15, 2009 · Mr B Loid
Oct 15, 2009 · Mr B Loid
Oct 15, 2009 · Mr B Loid
Oct 15, 2009 · Mr B Loid
Oct 15, 2009 · Mr B Loid
Oct 15, 2009 · Mr B Loid
Oct 15, 2009 · Mr B Loid
Oct 15, 2009 · Mr B Loid
Oct 15, 2009 · Mr B Loid
Oct 15, 2009 · Mr B Loid
Oct 15, 2009 · Mr B Loid
Oct 15, 2009 · Mr B Loid
Oct 15, 2009 · Mr B Loid
Oct 15, 2009 · Mr B Loid
Oct 15, 2009 · Mr B Loid
Oct 14, 2009 · Mr B Loid
Oct 12, 2009 · Mr B Loid
Be careful not to confuse LOC with productivity. In my experience (and, visibly, that of others as well), non-TDD development is much less focused, and results in (a) unnecessary (and ultimately unused) code, and (b) code that is less consise (probably due to the emphasis on refactoring in TDD). If you apply TDD from the outset, you actually don't have to "go through hoops", on the contrary it's quite a natural and fluid process.
That said, the extra time taken by the TDD teams suprises me a little - I suspect the fact that these teams were largely new to TDD may have contributed. The IBM approach to TDD, if you read the details, seems a little on the rigid side (UML and Sequence Diagrams for initial design, a test per method rather than a more BDD-style approach...). The Microsoft approach seems somewhat sub-optimal as well (the testing framework was run from the command line, and the resulting log files analysed...). So, these approaches to TDD are better than nothing. but far from an example of TDD at its best. From personal experience, I find that TDD, when done well, does not significantly add to development time - in fact, there are many cases where developers can easily get bogged down when not using TDD. For experienced TDDers, TDD helps maintain a smooth flow of development which is, at the end of the day, very productive.
Also, don't forget that it is very easy to write lots of lines of code quickly if you remove the constraint that it has to work - how much more time did it take to fix the extra bugs in the non-TDD code? Between 2.5 and 10 times as many bugs in the non-TDD code, that's quite a bit of fixing, especially if it's done some time after the code has been written.
Thanks for your comments!
Oct 10, 2009 · Mr B Loid
Apr 16, 2009 · Michael Bernat
Apr 16, 2009 · Michael Bernat
Apr 16, 2009 · Michael Bernat
Apr 16, 2009 · Michael Bernat
Feb 02, 2009 · royans tharakan
Feb 02, 2009 · royans tharakan
Feb 02, 2009 · royans tharakan
Feb 02, 2009 · royans tharakan
Feb 02, 2009 · royans tharakan
This is a tricky one. Teamcity and Pulse have the idea of "personal builds", but the implementation is a tad too intrusive for my liking (commits can only be done from the IDE and must go through the TeamCity server, for example). A more generic approach that I am investigating myself is to use development and integration branches in Subversion, along with the Subversion 1.5 merge features to "promote" changes automatically from the development branch to the integration branch if (and only if) the build succeeds. Still fairly experimental, though.
Jan 05, 2009 · admin
Hi Steven,
The 2008 Java Power Tools bootcamps were indeed well suited to organisations trying to get started with techniques like build automation, TDD and CI. The course is quite flexible, however, and the content and level of detail varies from session to session depending on the requirements and preferences of the students. The course is great for shops that still have little or no (or possibly out-of-date) built automation strategies in place (and there are more organisations of this type out there than you might think!). But I've also given the course to organisations and students who are more familiar with the basic concepts and many of the techniques, but who want to get up to speed in other areas (such as Maven 2, BDD, or distributed CI strategies), or who want to get a well-rounded picture of the state of the art in build automation, TDD, BDD, CI, and so forth.
One of the great things about the new 5-day format is that it gives more time to cover more advanced topics such as automated release and deployment strategies with Maven 2, Nexus and Hudson, advanced multi-module Maven projects, distributed builds, and more advanced TDD and BDD testing strategies.
In the new version of the Bootcampls, we cover unit and integration testing in Groovy and with easyb in a fair bit of detail, including web testing (selenium), database testing (dbunit) using Groovy and easyb, and web service testing using SoapUI.
We also cover more advanced CI integration strategies, including scaling CI, using CI with multiple SCM branches, automating deployment to different environments, coordinating releases with CI, integrating with tools like trac and JIRA, and so on.
I'm really looking forward to this season of bootcamps - I think it will be a lot of fun, and give enough time to both cover the basics and still get into some of the more advanced topics, or, for more advanced students, skim over the basics and concentrate on the advanced material in detail.
Jan 03, 2009 · admin
Hi Gian,
My best wishes for 2009 to you too!
The plans for the Europe/UK are still being made, but at this stage they will probably be towards the middle of the year (June or early July). There may be others as well - I'll publish more news as plans progress!
John.
Jun 16, 2008 · Dieter Komendera
Feb 27, 2008 · Harshad Oak
Feb 26, 2008 · Dietrich Kappe
Feb 26, 2008 · Dietrich Kappe
Feb 25, 2008 · Dietrich Kappe
Feb 25, 2008 · Dietrich Kappe
Feb 25, 2008 · Dietrich Kappe
Feb 21, 2008 · Geertjan Wielenga
Feb 18, 2008 · Chevol Davis
Feb 04, 2008 · Andrew Forward
Feb 04, 2008 · Andrew Forward
Feb 04, 2008 · Andrew Forward