我如何对这个使用控制台的 C# 方法进行单元测试?

2 c# testing methods unit-testing

我如何在代码中测试这个方法?我是否只需要在我拥有的输入中输入一个值或其他内容?它应该通过正确创建具有正确细节的歌曲来检查 ISD 是否正常工作

static Song InputSongDetails()
{
    Console.WriteLine("What is the name of your song");
    string name = Console.ReadLine();

    Console.WriteLine("What is the artists name");
    string artist = Console.ReadLine();

    int records;
    Console.WriteLine("How many records did it sell");
    while (!int.TryParse(Console.ReadLine(), out records) || records < 0)
    {
        Console.WriteLine("That is not valid please enter a number");
    }
    return new Song(name, artist, records);
}
Run Code Online (Sandbox Code Playgroud)

hai*_*770 6

最好的方法可能是抽象出Console使用某些接口。但是,您也可以使用所需的数据预先填充In缓冲区Console

例如:

var data = String.Join(Environment.NewLine, new[]
{
    "Let it be",
    "Beatles",
    // ...
});

Console.SetIn(new System.IO.StringReader(data));

// usage:
var songName = Console.ReadLine();
var artistName = Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)

参见MSDN