I would like to test an API, which received one argument and returns a set. The test invokes the API with an argument and checks if the returned set contains expected values.
Suppose, I have to test the API with arguments arg1, arg2, and arg3 and check if values a, b, c appear in the returned set. That is, my test case looks as follows:
- invoke the API with
arg1and check ifa,
b,cappear in the returned set. - invoke the API with
arg2and check ifa,
b,cappear in the returned set. - invoke the API with
arg3and check ifa,
b,cappear in the returned set.
How to develop this test case with Junit 4 ? What if I have to add arg4 ? What if I have to check if value d appear in the returned set ? Can I read the list of arguments and expected values from the configuration?
Fluent assertions
First of all, use FEST-Assertions library to introduce pleasantly looking assertions with meaningful error messages:
The BDD way
But I understand your question is not about the syntax, but about methodology: what should you do if
arg4needs to be tested? Well, ifarg1througharg4have a different semantic meaning, I would advice you to have a separate test for each argument. Very verbose, but also extremely readable (pseudocode):..and repeat this for every test. The key part is: method name should represent the meaning of an argument, what does this method actually test, what do you expect, what is the scenario?
Consider testing
isEvenmethod. I would recommend the following tests:shouldReturnTrueForZeroshouldReturnTrueForSmallPositiveEvenNumbershouldReturnTrueForLargePositiveEvenNumbershouldReturnFalseForSmallPositiveOddNumbershouldReturnFalseForLargePositiveOddNumberEach test represent a slightly different, well defined scenario. On the other hand you might generate literally thousands of
shouldReturnFalseWhen227, but what is the value of such a test suite, except it’s large? Test semantically different arguments and corner cases, defining precisesly what case is being tested.Parameterized way
If you really want to have just a single generic test method, Parameterized runner is the way to go. I think the example is self-explanatory. NB: you can parameterize expected values as well.
Based on this.