如何测试从 Console.ReadLine 读取的线程,即如何写入控制台的输入?

How to test a thread that reads from Console.ReadLine i.e. how do I write to the console's input?

我有一个通过 Console.ReadLine 从控制台读取的线程,但要为该线程构建单元测试,我想基本上写入控制台的输入,我试过这个:

Stream inputStream = Console.OpenStandardInput();
StreamWriter sw = new StreamWriter(inputStream);
sw.WriteLine("foo");

但是话题没有看到文字?还有别的办法吗?

我认为你需要在这件事上退一步。您所做的是将您的应用程序耦合到控制台。然而你真的应该把它分开......这是一些伪代码:

您的申请

public interface IUserInput
{
    string ReadInput();
}

public class ConsoleInput : IUserInput
{
    public ReadInput()
    {
        return Console.ReadLine();
    }
}

public class YourClass
{
    IUserInput _userInput;

    // Can inject TEST or REAL input
    public YourClass(IUserInput userInput)
    {
        _userInput = userInput;
    }

    // ... Your code
    public void YourMethod()
    {
        var doSomething = _userInput.ReadInput();
    }
}

你的测试

public class TestInput : IUserInput
{
    public ReadInput()
    {
        return "This is dummy data";
    }
}

[Test]
public void MyTest()
{
    var testInput = new TestInput();
    var systemUnderTest = new YourClass(testInput);
    // ...
}