我已经实现了代码,我必须对其进行单元测试。我有一个 Display() 方法,最后在控制台中打印。所以为了测试它,我必须断言控制台中打印的结果是预期的。这是 Display() 方法。
public void Display(int[] playerPosition)
{
StringBuilder matrixAsStringBuilder = new StringBuilder();
for (int row = 0; row < this.Rows; row++)
{
for (int col = 0; col < this.Cols; col++)
{
if (playerPosition[1] == row && playerPosition[0] == col)
{
matrixAsStringBuilder.Append(this.PlayerSymbol);
}
else
{
matrixAsStringBuilder.Append(this.matrix[row, col]);
}
if (col < this.Cols - 1)
{
matrixAsStringBuilder.Append(" ");
}
}
matrixAsStringBuilder.Append("\n");
}
Console.WriteLine(matrixAsStringBuilder.ToString());
}
我如何验证控制台的结果是否符合我的预期。再次感谢!
最佳答案
你不知道。让 Display
返回一个 String
,然后使用单独的方法将该字符串打印到控制台。您知道 Console.WriteLine()
有效,因此您只需测试执行处理的方法。
这也符合一般的编程准则:让一个方法做一件事。它不应该既处理数据又打印出来,至少因为这会诅咒方法命名:你称它为“显示”,但实际上它所做的不仅仅是显示。
关于c# - 如何断言控制台的结果与预期相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24474953/