Parameterized Tests

Suman Maity
3 min readJan 20, 2020

--

If you have found your way to this article, probably you’re a developer, fed up with writing tests. Unit testing is, after all, very time-consuming, and so, so redundant. So, how can we make writing tests easier and less onerous? 🤔

Let’s and try to understand what exactly are Parameterized Tests and when to use them?

Well, they allow us to execute one test as many times as we want, each with a set of different input and output values (parameters), without rewriting our tests.

The best part is that parameterized tests allow us to handle the edge case scenarios efficiently. Once you are done writing your first test with a normal set of parameters, you can easily add all the edge cases, such as parameter is null, the parameter doesn’t have the required field etc.

Now we know what they are and what are the advantages, let’s do some coding.

Let the code begin

Let’s assume we have following Junit tests, where we want to validate our isPalindrome function against three different inputs:

Why so redundant 🙁

As you can see in the above example, we had to write the same test thrice, one for each input we want to test. Very laborious right? Here, we had to write three tests for three different inputs but what if we had to write tests for ten inputs? or twenty? or more?

This current approach leads to redundancy. We write the same tests again and again for different scenarios, doing so we lose lots of time. We could have used that time to solve more complex/important problems. Here is where our new friend Parameterized Tests comes to rescue.

Let’s rewrite our tests by passing parameters

Here I am using Junit, it has a nice annotation “@ParameterizedTest” which allows us to write parameterized tests conveniently. Take a look at the following code -

Much better 🙂

As you can see here, we have re-written our previous (redundant, time-consuming and fat) tests to a simple stream of input text and expected outcome.

Tip: Use a good naming convention so that we can easily understand the test from reports itself.

Now if you want to add a new scenario it’s just a matter of adding a new set of arguments to the stream and you are done.

Conclusion

That’s all people! I hope you are able to understand the simplicity and efficiency of parametrised tests!

There are different libraries available in the market for different programming language, so you can use this concept in almost every language.

PS: I hope you’ve enjoyed it, and if you’ve found it useful, please feel free to share with others or leave a comment. 😃 Oh, you can also check my blogs to learn more about how to do parameterized tests in Java and Jest.

--

--

Suman Maity

Just a person who loves programming and want to learn new things related to it. Application Developer at ThoughtWorks ~ https://www.thoughtworks.com/