Parameterized test?
Since JUnit4 we can now run the parameterized test, but what does that mean? It means that we can run one test multiple times with different values, great isn’t it?
How to?
Yeah that great, but how can I do that?
That simple :
Annotate your test class with @RunWith(Parameterized.class)
Create method annotated with @Parameters that returns an Iterable of Objects as test data set.
Create a constructor that takes as a parameter what is equivalent to one row of your dataset. Or create instance variable that will be equivalent as one parameter and annotate them with @Parameter(X) where X is the parameter index in a row of the dataset.
Create a test case that will use your instance variable.
Ok, but concretely can I have an example?
Exemple
Class to test
Let’s take a simple class, that take a String literal of a calcul as parameter and return the result.
Classique Junit test
In a Classique way I wrote this test class to test each one of my case
As you can see, I have one test per test case, here as my class is simple, it doesn’t have that much line, but what if my class was more complexe, it will be a lot more code, redundant isn’t it?
Parameterized
Here is the same test, but parameterized, you can see all the previous statement established in the How-to section
The runner
The dataset
The parameters
-
The test who use it
Thanks for your reading time, the example in this article are in Junit4, if you want an exemple using Junit5, I will write another article about it.
Top comments (2)
Hi, here is how it is used at SystemDS, github.com/apache/systemds/blob/ma...
thanks, will read it later to improve how i do it.