我有以下井字游戏代码:
class TicTacToeBoard:
board = [[0,0,0], [0,0,0], [0,0,0]]
def printBoard(self):
print(self.board)
def putPiece(self, position1, position2):
self.board[position1][position2] = 1
我正在对代码进行单元测试,如下所示:
def testestablishTicTacToeBoard(self):
test = TicTacToeBoard()
self.assertEqual(test.board, [[0,0,0],[0,0,0],[0,0,0]])
def testPutPiece(self):
test = TicTacToeBoard()
self.assertEqual(test.board, [[0,0,0],[0,0,0],[0,0,0]])
test.putPiece(1,1)
self.assertEqual(test.board, [[0,0,0],[0,1,0],[0,0,0]])
在我进行第二个单元测试之前,第一个单元测试顺利通过。一旦我进行了第二个单元测试,第一个单元测试就不再通过:
self.assertEqual(test.board, [[0,0,0],[0,0,0],[0,0,0]])
AssertionError: Lists differ: [[0, 0, 0], [0, 1, 0], [0, 0, 0]] != [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
第二个单元测试中发生了什么导致第一个单元测试不再通过
它看起来像是因为电路板在所有实例之间共享(它是一个类属性,而不是实例属性)
您可以使用此更改类代码,它应该可以工作:
如果您想让自己相信真正发生的事情,可以比较两个版本(实例/类属性):
请注意,第二块tictactoe板
b2
没有位于(1, 2)
位置的板,而是位于(1, 2)
位置的板相关问题 更多 >
编程相关推荐