如何使用NUnit测试带有out或ref参数的方法?

pav*_*red 7 c# nunit console-application

如果我有一个接受out参数并接受输入表单控制台的函数 -

public void Test(out int a)
{
     a = Convert.ToInt16(Console.ReadLine());  
}
Run Code Online (Sandbox Code Playgroud)

在NUnit测试期间如何使用Console.Readline()接受输入?如何使用NUnit测试此方法?

我尝试将此代码用于我的NUnit测试用例 -

[TestCase]
public void test()
{
     int a = 0;   
     ClassAdd ad = new ClassAdd();
     ad.addition(out a);

     //a should be equal to the value I input through console.Readline()
     Assert.AreEqual(<some value I input>, a, "test");    
}
Run Code Online (Sandbox Code Playgroud)

如何测试接受out参数的方法并接受来自Console的用户输入?

Lee*_*Lee 3

您可以使用SetIn以下方法System.Console设置输入源:

StringReader reader = new StringReader("some value I input" + Enivronment.NewLine);
Console.SetIn(reader);

int a = 0;   
ClassAdd ad = new ClassAdd();
ad.addition(out a);

Assert.AreEqual(<some value I input>, a, "test");
Run Code Online (Sandbox Code Playgroud)

编辑:要测试多个值,只需用新行分隔每个输入:

string[] lines = new[] { "line1", "line2" };
StringReader input = new StringReader(String.Join(Environment.NewLine, lines));
Console.SetIn(input);

string input1 = Console.ReadLine();    //will return 'line1'
string input2 = Console.ReadLine();    //will return 'line2'
Run Code Online (Sandbox Code Playgroud)