gpt4 book ai didi

c# - NunitTest 控制台输出

转载 作者:行者123 更新时间:2023-11-28 20:53:16 25 4
gpt4 key购买 nike

我正在尝试 Nunit 测试一个方法,我断言我得到了正确的输出,但问题是每次代码跳入:

Console.SetCursorPosition(xOffset, yOffset++);

显然你不能重定向 SetCursorPosition,所以我的问题是:..“无论如何我可以合理地对这个方法进行单元测试”

    public void Execute()
{
int xOffset = 84;
int yOffset = 3;
Console.SetCursorPosition(xOffset, yOffset++);
Console.WriteLine("Events");

string header = "| LogType | Message | tagCollection | Time |";

Console.SetCursorPosition(xOffset, yOffset++);
Console.WriteLine(header);

Console.SetCursorPosition(xOffset, yOffset++);
Console.WriteLine(new string('-', header.Length));

if (!string.IsNullOrWhiteSpace(Status))
{
Console.SetCursorPosition(xOffset, yOffset++);
Console.WriteLine(Status);
}

foreach (string str in NotificationList)
{
Console.SetCursorPosition(xOffset, yOffset++);
Console.WriteLine(str);
}
}

这是我的测试:

    [Test]
public void NotificationDisplayer_inputTestString_ExpectedResult()
{

using (StringWriter sw = new StringWriter())
{
Console.SetOut(sw);
uutNotificationDisplayer.Execute();
Assert.That(sw.ToString()), Is.EqualTo(expectedResult));
}
}

最佳答案

代码在一个地方做两件事导致了问题。

您想在您的方法中构造一个字符串并打印它。他们应该分开。测试用例感兴趣的是字符串是否正确构造,而不是 Console.WriteLineConsole.SetCursorPosition 是否正常工作。因此,让我们将代码分开,如下所示。

static void Main(string[] args)
{
var messages = GetMessagesToPrint();
Execute(84, 3, messages);
}

// Method for which you should write the test method on its output
private static List<string> GetMessagesToPrint()
{
string header = "| LogType | Message | tagCollection | Time |";
...
...// actual list of string you want to construct.
...
var messages = new List<string> {"Events", header, new string('-', header.Length)};
return messages;
}

//This doesnt need a test method
public static void Execute(int xOffset, int yOffset, IEnumerable<string> messageToPrint)
{
foreach (var message in messageToPrint)
{
Console.SetCursorPosition(xOffset, yOffset++);
Console.WriteLine(message);
}
}

然后您可以为 GetMessagesToPrint 编写单元测试,而不必担心 System.Console 方法。

关于c# - NunitTest 控制台输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36742489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com