C# 如何对这个函数进行单元测试

C# 如何对这个函数进行单元测试,c#,unit-testing,C#,Unit Testing,我有办法。我想用单元测试来测试这个方法。测试这种方法的好方法是什么 public class ChoiceOption { public static int Choice(string message, string errorMessage) { while (true) { try { Console

我有办法。我想用单元测试来测试这个方法。测试这种方法的好方法是什么

public class ChoiceOption
    {
        public static int Choice(string message, string errorMessage)
        {
            while (true)
            {
                try
                {
                    Console.Write(message);
                    string userInput = Console.ReadLine();
                    if (userInput == string.Empty)
                    {
                        userInput = "0";
                    }
                    return int.Parse(userInput);
                }
                catch (Exception)
                {
                    Console.WriteLine(errorMessage);
                }
            }
        }
    }

您应该首先介绍预期的“正确”案例。在本例中,这将是几个数字(可能是0、正数和负数)

此时,您可以尝试边缘情况:

  • “你好”

  • “c”

  • 2.5

  • 2^63

  • 真的

  • “”


这些都是我能想到的直接例子,但最终你的单元测试和你的创造力一样强大。首先,重写你的方法,使其可以进行单元测试,而不依赖于控制台输入和输出,例如

public class ChoiceOption
{
    private readonly Func<string> readLine;
    private readonly Action<string> writeLine;

    public ChoiceOption(Func<string> readLine, Action<string> writeLine)
    {
        this.readLine = readLine;
        this.writeLine = writeLine;
    }

    public int Choice(string message, string errorMessage)
    {
        while (true)
        {
            writeLine(message);
            string userInput = readLine();
            if (string.IsNullOrEmpty(userInput)) return 0;
            if (int.TryParse(userInput, out int result))
            {
                return result;
            }
            writeLine(errorMessage);
        }
    }
}

首先,您应该将方法更改为,以使测试更容易(例如,无模拟等),因此您需要提取方法之外的用户输入,理想情况下还需要打印到控制台。现在,您可以模拟测试中的用户输入,还可以断言异常:

public class ChoiceOption
{
    public static int Choice(string userInput, string message, string errorMessage)
    {
        if (userInput == string.Empty)
        {
            userInput = "0";
        }
        return int.Parse(userInput);
    }
}

现在,它很容易测试。循环、用户输入和异常捕获将在此方法的调用方中。这是您的生产代码,也是您的单元测试。

我编写了一个这样的测试函数,但它不起作用。你能给我举个例子吗。感谢[Test]公共静态无效选项\u正常\u有效参数(字符串消息、字符串错误消息、int输出){message=“a”errorMessage=“a”output=1;Assert.AreEqual(output,ChoiceOption.Choice(message,errorMessage));}我认为使用NUnit测试并不是一个很好的单元测试候选者。使其成为非静态的,并为
控制台注入依赖项。编写
控制台。读取行
,然后您可能可以对其进行“单元”测试。
public class ChoiceOption
{
    public static int Choice(string userInput, string message, string errorMessage)
    {
        if (userInput == string.Empty)
        {
            userInput = "0";
        }
        return int.Parse(userInput);
    }
}