Question

Can someone explain why and when to write parameterized test cases?

Was it helpful?

Solution 2

Parameterized tests are used in situations where one needs to perform exactly the same test using a large number of different input values.

A good example might be testing a piece of code that performs a calculation, where you have a large collection of known-correct answers that you would like to test.

OTHER TIPS

So, I would like to add to Duncan's answer in this way. Whenever you have a case where you would like to test multiple input values to test a method you basically have three options: 1) copy / paste. 2) Parameterized 3) Theories.

Obviously copy / paste is the wrong answer. Both Theories and Parameterized allow for running the same test(s) multiple times with different input. In general I suggest using Theories over Parameterized if the correct output of the test can be determined / calculated from the input. This is because when using Theories, you can mix @Theory and @Test and only the Theories will be run multiple times. This is unlike Parameterized where EVERY test in the class will be run once per input. So if you have two tests, one that uses the input and one that does not, both are executed n times.

Another advantage of Theories is the ability to use @TestedOn to pass values in-line to a specific theory.

 @Theory
 public void theoryTest(@TestedOn(ints={-1,0,1,2,55} int input){...}

TestedOn explained

I have a GitHub project that includes @TestOn that allows for ints, booleans, Strings, etc.

The only time I suggest using Parameterized over Theories is where it is not easy to calculate the expected output from the input and it must therefore be explicitly provided. One solution to get around the issue with running all tests multiple times is to used the Enclosed runner and put all the parameterized tests in one inner class and the non-parameterized tests in another.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top