【问题标题】:How to assert that the result from console is the same as expected?如何断言控制台的结果与预期的相同?
【发布时间】:2014-06-29 17:55:39
【问题描述】:

我已经实现了代码,我必须对其进行单元测试。我有一个 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());
        }

如何验证控制台的结果是否符合我的预期。再次感谢!

【问题讨论】:

  • 我认为你最好重写这个方法让它返回一个字符串,而不是控制台编写它。这样你就可以断言结果值,而且你可以增加你的方法的可扩展性。

标签: c# unit-testing


【解决方案1】:

你没有。让Display 返回一个String,然后以单独的方法将该字符串打印到控制台。您知道 Console.WriteLine() 有效,因此您只需测试执行处理的方法即可。

这也符合一般编程准则:让一种方法做一件事。它不应该同时处理数据并将其打印出来,至少因为这会诅咒方法命名:你称它为“显示”,但实际上它不仅仅是显示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    相关资源
    最近更新 更多