So, I have a JUnit test for Uncle Bob's classic Bowling game example for TDD.
I refactored the test to use an array of games and expected scores.
The advantage is it's easy to add new tests.
The disadvantage is that it doesn't "self document" the code or the test.
Are there any best practices surrouding this?
public class ScoreTest {
int[][] games = {
{0,0,0,0,0,0,0,0,0,0},
{10,10,10,10,10,10,10,10,10,10,10,10
};
int[] scores = {0, 300};
@Test
public void testScore() {
for(int i=0; i<games.length; i++) {
let game = games[i];
let expectedScore = scores[i];
let score = new Score();
score.roll(game); // roll the entire game
let actualScore = score.total() // calculate the bowling score
assertEquals(expectedScore, actualScore);
}
}
}
I think that if one does want to go down the path of "input x
should produce output y
"-tests, then one will not get much more readable as this. I would only recommend those kind of tests for trivial problems or well-known sequences (e.g. tests for something producing the fibonacci sequence).
For everything more complex, I would advice to use a behaviour-driven approach with, e.g., Given-When-Then tests. Those tests tend to be more expressive and more self-documenting.
A remark: If you are using JUnit5, I would propose to use parameterized tests.