JUnit is a popular testing framework for writing unit tests in Java projects. Every software engineer should always try to consider using less code to achieve objectives and the same is true for test code. This post shows one way to write less test code by increasing code re-use using JUnit 4 annotations.
Ok, so let's set the scene. You have a bunch of tests that are very similar but vary only slightly in context. For example, let's say you have three tests which do pretty much the same thing. They all read in data from a file, and count the number of lines in the file. Essentially you want the one test to run three times, but read
a different file and test for a specific amount of lines each time.
This can be achieved in an elegant way in JUnit 4 using the @RunWith and @Parameters annotations. An example is shown below.
W.R.T. to code above:
Enjoy...
Ok, so let's set the scene. You have a bunch of tests that are very similar but vary only slightly in context. For example, let's say you have three tests which do pretty much the same thing. They all read in data from a file, and count the number of lines in the file. Essentially you want the one test to run three times, but read
a different file and test for a specific amount of lines each time.
This can be achieved in an elegant way in JUnit 4 using the @RunWith and @Parameters annotations. An example is shown below.
W.R.T. to code above:
- The RunWith annotation tells JUnit to run with Parameterized runner instead of the default runner.
- The @Parameters annotation is defined by the JUnit class org.junit.runners.Parameterized.
It is used to define the parameters that will be injected into the test.
- The data() method is annotated with the parameters annotation. It defines a two dimensional array. The first array is: "players10.txt", 10. These parameters will be used the first time the test is run. "players10.txt" is the file name. 10 is the expected number of rows.
Enjoy...
The only thing I hate about JUnit's parametrized tests is that, the whole class considered as parametrized one, where I only wish to make some selected methods parametrized.
ReplyDeleteThe problem is, if I add another test method which is not parametrized to this class, it also get executed for that no of parameters.
Same thing is in TestNG and its more intitutive because parameters are applied on individual methods and not on whole class.
I have no words for this great post such a awe-some information i got gathered. Thanks to Author.
ReplyDeletehtml5 video player| html5 video player