我写了两种格式的代表主板的迷你检查器:long positionID
和byte[][] board
。前者更便宜,后者更易于表现/操纵。转换本身很简单(请参阅下面的代码)。测试驱动开发。如何在创建方法之前为此转换编写单元测试?
TDD状态“写入一个失败的测试,然后写入生产代码”。如何进行表示转换?单元测试如
assertEquals(0L, toIndex(new byte[6][6]))
不提供太多的报道。测试Long myPosID = 42L; assertEquals(myPosID, toIndex(toBoard(myPosID))
不会增加太多价值。测试整个范围将永远持续下去。几个随机myPosID
值(蒙特卡洛模拟)运行单元测试似乎更好,但即使通过测试并没有多大意义。
TDD应该怎么做?
/*
This class manipulates checkers board representation. Position is stored as long and represented as byte[height][width] board.
For board representation white = 0, black = 1, empty = 2.
Long positionID to byte[][] board:
get ternary numeral system representation of positionID, place positional values to corresponding squares.
For conversion from byte[][] board to long positionID:
long positionID = 0; for each (byte playableSquare : board){playable square positionID = positionID*3. positionID+= playableSquare}
*/
public final int boardHeight = 6;
public final int boardWidth = 6;
public long toIndex(byte[][] board) {
byte coords[] = new byte[boardHeight * boardWidth/2];
int totalSquares = boardHeight * boardWidth/2;
byte k = 0;
for (int i = 0; i < boardHeight; i++) {
for (int j = 0; j < boardWidth/2; j++) {
byte makeItCheckers = (byte) ((i + 1) % 2);
coords[k] = board[i][j * 2 + makeItCheckers];
k++;
}
}
long positionID = 0;
for (int i = totalSquares - 1; i >= 0; i--) {
positionID = positionID * 3 + coords[i];
}
return positionID;
}
public byte[][] toBoard(long positionID) {
int totalSquares = boardHeight * boardWidth/2;
int[] coords = new int[totalSquares];
for (int i = 0; i < totalSquares; i++) {
coords[i] = (int) (positionID % 3L);
positionID = positionID/3L;
}
byte[][] board = new byte[boardHeight][boardWidth];
Arrays.fill(board, 2);
byte k = 0;
for (int i = 0; i < boardHeight; i++) {
for (int j = 0; j < boardWidth/2; j++) {
byte makeItCheckers = (byte) ((i + 1) % 2);
board[i][j * 2 + makeItCheckers] = (byte) coords[k];
k++;
}
}
return board;
}
是的,在TDD中,您首先编写一个失败的测试,然后编写通过测试的生产代码。我先写了我的代码。现在我想,TDD将会如何。他们在开始时不会有转换功能或测试。他们会写一个测试。测试会是什么样子? – Stepan
当您执行TDD时,并不意味着您通过预先知道您将需要的所有处理。对于您的应用程序,业务需求将首先以TDD编码。正常:你从最初的业务需求开始,然后开始编写测试然后执行。一次,在开发过程中,出现了更好的需求或技术需求(这里将数据从格式转换为另一种格式),您必须完成最初的业务需求。所以你在TDD中指定它们。 – davidxxx
让我们将这个逻辑应用于我的问题。我需要一个TEST,后来有一种方法从“Long positionID”的十进制表示到三进制数字系统,转换为“对于'positionID'的三进制数字表示中相应位置的每个方形赋值”。如何写这个测试?!。它或者不包括任何东西(检查0L,1L,2L并且说“我们通过!万岁!” - 我们假设一个测试并欺骗大学)或者它永远运行。方法本身是微不足道的。但是如果测试很难写,TDD的意义何在? – Stepan