Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply unit testing to C# function which requires user input dynamically?

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

like boundary value analysis ...

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

Programmatically hint will be great help!

like image 737
rana Avatar asked Apr 16 '12 20:04

rana


People also ask

How is unit testing implemented in C?

Define the function within the unit test file itself, probably at the top of the file. If it is a C function being called by C code, place it within the extern "C" {} section. As a last resort, one can compile out the function calls and implementations using a define for unit tests. e.g. #if !

Does C have unit testing?

A Unit Testing Framework for CCUnit is a lightweight system for writing, administering, and running unit tests in C. It provides C programmers a basic testing functionality with a flexible variety of user interfaces.


1 Answers

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.

Edit for 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());
 }
like image 127
Josh Avatar answered Oct 18 '22 06:10

Josh