Alternative to JUnit Parameterized Classes: junit-dataprovider
Join the DZone community and get the full member experience.
Join For Freewe all know junit test-classes can be parameterized , which means that for a given set of test-elements, the test class is instantiated a few times, but using constructors for that isn’t always what you want.
i’ve taken the stringsorttest from this blog as an example.
@runwith(parameterized.class) public class stringsorttest { @parameters public static collection<object[]> data() { return arrays.aslist(new object[][] { { "abc", "abc" }, { "cba", "abc" }, }); } private final string input; private final string expected; public stringsorttest(final string input, final string expected) { this.input = input; this.expected = expected; } @test public void testsort() { assertequals(expected, mysortmethod(input)); } }this is pretty darn obnoxious sometimes if you have multiple sets of data for various tests, which all go through the constructor, which would force you to write multiple test classes. testng solves this better by allowing you to provide separate data sets to individual test methods using the @dataprovider annotation .
but don’t worry, now you can achieve the same with the junit-dataprovider , available on github. pull in the dependency with e.g. maven.
<dependency> <groupid>com.tngtech.java</groupid> <artifactid>junit-dataprovider</artifactid> <version>1.5.0</version> <scope>test</scope> </dependency>the above example now could be rewritten as:
@runwith(dataproviderrunner.class) public class stringsorttest { @dataprovider public static object[][] data() { return new object[][] { { "abc", "abc" }, { "cba", "abc" }, }; } @test @usedataprovider("data") public void testsort(final string input, final string expected) { assertequals(expected, mysortmethod(input)); } }you’ll see: no constructor. in this example it doesn’t have many benefits, except maybe for less boiler-plate, but now you can create as many @dataprovider-annotated methods which are fed directly to your @usedataprovider-annotated testmethod(s).
sidenote for eclipse: if you’re using that ide, the junit plugin is unable to map the names of the passed/failed testmethods to the ones in the testclass correctly. if a method fails, you’ll have to find it back manually in the testclass (or vote for the patch andreas smidt created to get this fixed in eclipse).
in the mean time, if you’re stuck with junit and you’d love to use this feature you’re so accustomed to using with testng, go ahead and try the junit-dataprovider now.
Published at DZone with permission of Ted Vinke. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments