How to apply unit testing to a C # function that requires dynamic user input?

The function below introduces the user. I need to check this function using Unit Testing. Can someone tell me how to test a feature that requires dynamic user input. Thanks

like boundary value analysis...

numberOfCommands it should be (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;
}

A software hint will be a big help!

+5
source share
5 answers

Create an interface and pass the interface to receive the text. Then, in unit test, go to the mock interface, which automatically returns some result.

Change code details:

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

Two essential things:

  • Console.ReadLine ​​ - ( )
  • Console.ReadLine TextReader ,

, TextReader ( , ):

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

Get_Commands :

    int commandsNumber = Get_Commands(Console.In);

unit test , , , 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));
}
+2

. , .

" " /, , " ", , " ", , , .

0

Main() :

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

, , . , ?

0

Console.SetIn() Console.SetOut() . StringReader StringWriter .

You can see my blog post on this subject for a more complete explanation and example: http://www.softwareandi.com/2012/02/how-to-write-automated-tests-for.html

0
source

All Articles