Currently I have to create a parameterized test class for every method that I want to test with several different inputs. Is there a way to add this together in one file?
Right now there's CalculatorTestAdd.java
which has a set of parameters that are used to check if the Add()
function works properly. Is there a possbility for me to 'connect' this set to the Add()
function and create an additional set meant for the Subtract()
method and add this method in the same test class, resulting in one file called CalculatorTest.java
?
Yes. There's nothing special you have to do. For every set of value(s) of the parameters, each @Test method is run once, so just have one method test add() and another method test subtract().
May I also add that the person who is dictating this requirement is misguided. There is little value in dictating certain design patterns "for all cases" - might as well hire trained monkeys.
Another pure JUnit but yet elegant solution in my view is to encapsulate each parameterized test(s) in their own inner static class and use the Enclosed test runner on the top level test class. This allows you not only to use different parameter values for each test independently of each other but also to test methods with completely different parameters.
This is how it would look like:
Note the usage of the
@Parameter
annotation in theSubstractTest
, which I consider more readable. But this is more a matter of taste.Well, now JUnit-5 offers you a solution for this - by redefining a way to write parameterized tests. Now a parameterized test can be defined at a method level using @ParameterizedTest and can be given a method source using @MethodSource.
So in your case you can have 2 separate data source methods for providing input data for your add() and subtract() test methods, both in the same class. Your code should go something like this:
}
This answer is similar to Tarek's one (the parametrized part), although I think it is a bit more extensible. Also solves your problem and you won't have failed tests if everything is correct:
you can use parameters with https://github.com/piotrturski/zohhak:
if you want to load parameters from file, you can use http://code.google.com/p/fuzztester/ or http://code.google.com/p/junitparams/
and if you need real flexibility you can use junit's @Parameterized but it clutters your code. you can also use junit's Theories - but it seems an overkill for calculator tests