如何将单元测试应用于需要用户动态输入的C#函数? [英] How do I apply unit testing to C# function which requires user input dynamically?
本文介绍了如何将单元测试应用于需要用户动态输入的C#函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的功能从用户那里获取输入.我需要使用Unit Testing
测试此功能.谁能告诉我如何测试这种需要用户动态输入的功能.谢谢
The function below gets input from the user. I need to test this function using Unit Testing
. Can anyone tell me how to test this kind of function which require user input dynamically. Thanks
像boundary value analysis
...
numberOfCommands
应该是(0 <= n <= 100)
public static int Get_Commands()
{
do
{
string noOfCommands = Console.ReadLine().Trim();
numberOfCommands = int.Parse(noOfCommands);
}
while (numberOfCommands <= 0 || numberOfCommands >= 100);
return numberOfCommands;
}
以编程方式提示将大有帮助!
Programmatically hint will be great help!
推荐答案
创建一个接口,并传入该接口以接收文本.然后,在单元测试中,传递一个模拟接口,该接口会自动返回一些结果.
Create an interface and pass in the interface to receive text. Then, in your unit test, pass in a mock interface that automatically returns some result.
编辑代码详细信息:
public interface IUserInput{
string GetInput();
}
public static int Get_Commands(IUserInput input){
do{
string noOfCommands = input.GetInput();
// Rest of code here
}
}
public class Something : IUserInput{
public string GetInput(){
return Console.ReadLine().Trim();
}
}
// Unit Test
private class FakeUserInput : IUserInput{
public string GetInput(){
return "ABC_123";
}
}
public void TestThisCode(){
GetCommands(new FakeUserInput());
}
这篇关于如何将单元测试应用于需要用户动态输入的C#函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文