将TDD重构为一系列测试

问题描述

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

我将测试重构为使用一系列游戏和预期得分。

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

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

有没有解决此问题的最佳做法?

public class scoreTest {
int[][] games = {
  {0,0},{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);
  }
}
}

解决方法

您可以代替一个int [] []来创建一个小的内部类,并对其进行排列。

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

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

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

此外,这摆脱了您尝试维护两个并行阵列的想法,这总是一个坏主意。

,

我认为,如果确实想走“ 输入x应该产生输出y ”-测试的道路,那么人们的可读性就不会高得多这样。我只会推荐针对琐碎问题或众所周知序列的测试(例如针对产生fibonacci sequence的东西的测试)。

对于所有更复杂的事情,我建议使用行为驱动的方法,例如Given-When-Then tests。这些测试往往更具表现力和更多的自我证明。


备注:如果您使用的是JUnit5,我建议使用parameterized tests