如何将单元测试应用于需要动态用户输入的C#功能?

时间:2012-04-16 20:45:01

标签: c# unit-testing input tdd

以下功能获取用户的输入。我需要使用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;
}

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

5 个答案:

答案 0 :(得分:11)

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

编辑代码详细信息:

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

答案 1 :(得分:2)

两件必不可少的事情:

  1. Console.ReadLine是一个外部依赖项,应该以某种方式提供到您的方法中(最好通过依赖注入)
  2. Console.ReadLine使用了TextReader基类,以及应该提供的内容
  3. 所以,你的方法需要的是对TextReader的依赖(你可以用自定义界面抽象它更多,但为了测试它就足够了):

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

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

        int commandsNumber = Get_Commands(Console.In);
    

    在单元测试中,您使用例如StringReader class:

    创建虚假输入
    [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));
    }
    

答案 2 :(得分:1)

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

您可以在此主题上看到我的博文,以获得更完整的解释和示例:http://www.softwareandi.com/2012/02/how-to-write-automated-tests-for.html

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

在Main()中你可以这样做:

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

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