【问题标题】:NunitTest a ConsoleOutputNunitTest 控制台输出
【发布时间】:2016-04-20 11:31:35
【问题描述】:

我正在尝试 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));
        }
    }

【问题讨论】:

  • 为什么不做一个模拟方法并改变 y 的偏移值?因为从技术上讲,这就是您要在测试中验证的内容。不仅如此,您能否也给我们您的单元测试!!

标签: c# unit-testing testing nunit


【解决方案1】:

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

你想在你的方法中构造一个字符串并打印它。他们应该分开。测试用例是否对字符串的构造是否正确感兴趣,而不是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 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    相关资源
    最近更新 更多