Writing parameterized unit tests in Java using JUnit and JUnitParams
Sometimes when writing unit tests you have to test the same unit of code with many different input values. This can seem a bit redundant, and is where parameterized unit tests come in. This short example will show you how to use JUnit and JUnitParams to write such tests. Parameterized unit tests are supported in JUnit itself, and while there are a lot of other libraries available, I prefer JUnitParams because it is easy to use, has a lot of functionality and requires very little boilerplate code. In this example we use Maven to manage dependencies and build the project.
Let us start by adding dependencies to JUnit and JUnitParams to our pom.xml
file.
To simplify the example the code we are testing are really basic. We are testing a method that checks whether a String is blank or not. The implementation might not be perfect, but that that is irrelevant for the case of this example.
If we where not to use parameterized unit tests for this method, the test may have looked something like this.
As you can see, this can quickly get pretty verbose/unreadable/ugly if you have a lot of input values that you need to test. Another downside by doing it this way is that if the test breaks, it is not super easy to see which of the assertions that broke the test. The only way we have to find the broken assertion is to look at the line number in the stack trace. In this case, line 76.
By using parameterized unit tests, we can eliminate a lot of the repetavive code and make the tests a lot more readable by moving all of the input values we need to test out of the test method and into an annotation or in this case its own private method.
Now it is easy to see the test result for each individual input value that we are testing, and we can easily see that it was the last input value that broke the test.
If you want to see other examples of writing parameterized unit tests with JUnitParams, you can have a look at the documentation.