12

下面的函数从用户那里获取输入。我需要使用Unit Testing. 谁能告诉我如何测试这种需要用户动态输入的功能。谢谢

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;
}

以编程方式提示将有很大帮助!

4

5 回答 5

14

创建一个接口,传入接口接收文本。然后,在您的单元测试中,传入一个自动返回一些结果的模拟接口。

编辑代码细节:

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());
 }
于 2012-04-16T20:55:47.937 回答
3

两个基本的东西:

  1. Console.ReadLine是一个外部依赖,应该以某种方式提供给你的方法(最好通过依赖注入)
  2. Console.ReadLine在底层使用TextReader基类,这就是应该提供的

所以,你的方法需要的是依赖TextReader(你可以用你的自定义接口进一步抽象它,但为了测试它就足够了):

 public static int Get_Commands(TextReader reader)
 {
     // ... use reader instead of Console
 }

Get_Commands现在,在真实应用程序中,您使用真实控制台调用:

    int commandsNumber = Get_Commands(Console.In);

在您的单元测试中,您使用例如StringReader类创建假输入:

[Test]
public void Get_Commands_ReturnsCorrectNumberOfCommands()
{
   const string InputString = 
       "150" + Environment.NewLine + 
       "10" + Environment.NewLine;
   var stringReader = new StringReader(InputString);

   var actualCommandsNumber = MyClass.Get_Commands(stringReader);

   Assert.That(actualCommandsNumber, Is.EqualTo(10));
}
于 2012-04-17T10:24:30.153 回答
3

您可以使用Console.SetIn()andConsole.SetOut()来定义输入和输出。使用 StringReader 定义测试的输入,使用 StringWriter 捕获输出。

您可以查看我关于该主题的博客文章,以获得更完整的解释和示例: http: //www.softwareandi.com/2012/02/how-to-write-automated-tests-for.html

于 2012-04-18T11:41:02.420 回答
1

您可以将输入从文件重定向到标准输入,并在测试中使用它。您可以在程序本身中以编程方式执行此操作,也可以通过运行程序的 shell 执行此操作。

您还可以将所有“用户输入”外推到他们自己的类/函数中,这样就可以轻松地将“从用户那里获取一行文本”的函数替换为“返回此硬编码字符串以进行测试”的函数。如果这些函数中的每一个都在实现公共接口的类中,则可以很容易地将它们切换出来。

于 2012-04-16T20:56:01.260 回答
-1

在 Main() 你可以这样做:

int testCommand=Get_Commands();
Console.WriteLine(testCommand);

但是,我不知道这是否是您想要的测试类型。除了简单地测试函数的结果之外,还有更多的问题吗?

于 2012-04-16T20:58:49.053 回答