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

标签 c# nunit console-application

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

public void Test(out int a)
{
     a = Convert.ToInt16(Console.ReadLine());  
}

如何在 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");    
}

如何测试接受输出参数并接受来自控制台的用户输入的方法?

最佳答案

您可以使用System.ConsoleSetIn 方法来设置输入源:

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");

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

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'

关于c# - 如何使用 NUnit 测试带有 out 或 ref 参数的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3487696/

相关文章:

msbuild - hudson : warning MSB3245: Could not locate the assembly “nunit.framework”

c# - 键值对作为控制台应用程序中的参数

php - "X"参数不存在

unit-testing - 如何测试我的存储库实现?

c# - 使用 selenium Web 驱动程序在 Visual Studio 中测试本地项目

c# - 确保只有计划任务可以调用 Controller 操作

c# - 在 UWP 中在后台播放音频的最简单方法是什么?

c# - 在控制台应用程序中随时捕获用户 key

c# - Xamarin - 找不到类(android 支持库)

c# - 一个表单中的多个页面? C#