首页 > 解决方案 > 将 TDD 重构为一系列测试

问题描述

因此,我对鲍勃叔叔的经典保龄球游戏示例进行了 JUnit 测试,用于 TDD。

我重构了测试以使用一系列游戏和预期分数。

优点是添加新测试很容易。

缺点是它不会“自我记录”代码或测试。

有没有围绕这一点的最佳实践?

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);
  }
}
}

标签: javatestingjunittdd

解决方案


您可以创建一个小的内部类,而不是 int[][],并创建一个数组。

private static class BowlingTestGame {
    private String name;
    private int[] game;
    private int expectedResult;
}

BowlingTestGame[] games = {
    {"Perfect Game", {10,10,10,10,10,10,10,10,10,10,10,10}, 300},
    //  ... more tests ...
}

然后,您可以在断言中包含游戏名称作为失败消息。

此外,这可以避免您尝试维护两个并行数组,这总是一个坏主意。


推荐阅读