将 TDD 重构为一组测试
Refactoring TDD down to an array of tests
因此,我对 Bob 叔叔的 TDD 经典保龄球游戏示例进行了 JUnit 测试。
我重构了测试以使用一系列游戏和预期分数。
优点是很容易添加新的测试。
缺点是它不会“自我记录”代码或测试。
关于这方面有什么最佳实践吗?
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);
}
}
}
而不是一个 int[][],你可以做一个小的内部 class,然后做一个数组。
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 ...
}
然后您可以在断言中包含游戏名称作为失败消息。
此外,这使您摆脱了试图维护两个并行数组的麻烦,这总是一个坏主意。
我认为如果一个人确实想沿着“输入x
应该产生输出y
”的路径走下去-测试,那么一个人会没有比这更具可读性了。我只会推荐那些针对琐碎问题或 well-known 序列的测试(例如测试产生 fibonacci sequence 的东西)。
对于更复杂的事情,我建议使用 behaviour-driven 方法,例如 Given-When-Then tests。这些测试往往更具表现力,也更 self-documenting.
备注:如果你用的是JUnit5,我建议用parameterized tests。
因此,我对 Bob 叔叔的 TDD 经典保龄球游戏示例进行了 JUnit 测试。
我重构了测试以使用一系列游戏和预期分数。
优点是很容易添加新的测试。
缺点是它不会“自我记录”代码或测试。
关于这方面有什么最佳实践吗?
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);
}
}
}
而不是一个 int[][],你可以做一个小的内部 class,然后做一个数组。
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 ...
}
然后您可以在断言中包含游戏名称作为失败消息。
此外,这使您摆脱了试图维护两个并行数组的麻烦,这总是一个坏主意。
我认为如果一个人确实想沿着“输入x
应该产生输出y
”的路径走下去-测试,那么一个人会没有比这更具可读性了。我只会推荐那些针对琐碎问题或 well-known 序列的测试(例如测试产生 fibonacci sequence 的东西)。
对于更复杂的事情,我建议使用 behaviour-driven 方法,例如 Given-When-Then tests。这些测试往往更具表现力,也更 self-documenting.
备注:如果你用的是JUnit5,我建议用parameterized tests。