[英]How can I use NUnit to test a method with out or ref parameters?
If I have a function which accepts an out parameter and accepts an input form console - 如果我有一个接受out参数并接受输入表单控制台的函数 -
public void Test(out int a)
{
a = Convert.ToInt16(Console.ReadLine());
}
How can I accept an input using Console.Readline() during NUnit test? 在NUnit测试期间如何使用Console.Readline()接受输入? How can I use NUnit to test this method?
如何使用NUnit测试此方法?
I tried using this code for my NUnit test case - 我尝试将此代码用于我的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");
}
how can I test a method which accepts an out parameter and also accepts an user input from Console? 如何测试接受out参数的方法并接受来自Console的用户输入?
You can use the SetIn
method of System.Console
to set the the input source: 您可以使用
System.Console
的SetIn
方法来设置输入源:
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");
EDIT: To test multiple values, just separate each input with a new line: 编辑:要测试多个值,只需用新行分隔每个输入:
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'
There are 2 slightly different issues combined here. 这里有两个略有不同的问题。
The craziest thing to note is that you want to test a method that takes input from the console. 最值得注意的是,您要测试从控制台获取输入的方法。 Ie this implies user interaction.
即这意味着用户交互。 This is hardly the way to go about "automated testing" don't you think?
这不是“自动化测试”的方式你不觉得吗?
In answer to #2, I suggest you look at some of Misko Hevery's articles and videos on writing testable code. 在回答#2时,我建议你看看Misko Hevery的一些关于编写可测试代码的文章和视频。
http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/ http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/
For a brief summary specfic to your problem: 有关您的问题的简要摘要:
MethodToTest
currently wants input from the console. MethodToTest
当前需要来自控制台的输入。 MethodToTest
should take an "input stream" in its constructor. MethodToTest
的类应该在其构造函数中使用“输入流”。 (This is a technique called dependency injection.) [TestCase]
public void test()
{
<use appropriate type here> MockInputStream = new ...;
ClassToTest testClass = new ClassToTest(MockInputStream);
int Actual = 0;
MockInputStream.PutNextInput("4");
ClassToTest.MethodToTest(out Actual);
Assert.AreEqual(4, Actual, "MockInputStream placed 4 as the next value to read");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.