Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test a console program that reads input and writes to the console [closed]

Let's say I have a simple program like

using System;

public class Solution
{
    public static void Main(string[] args)
    {
        int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
        Array.Sort(arr);
        Console.WriteLine(string.Join(" ", arr));
    }
}

which I want to test in a separate project like

[TestMethod]
public void TwoNumbersDescendingAreSwapped()
{
     string input = "2 1";
     string expectedOutput = "1 2"; 
     // ... ???
     Assert.AreEqual(expectedOutput, actualOutput);
}

Is it possible to do that without actually using the .exe from Solution?

like image 246
user7127000 Avatar asked Apr 01 '17 19:04

user7127000


1 Answers

Move the code that does all the work in Main() to its own class and method:

public static class InputConverter
{
    public static string ConvertInput(string input)
    {
        int[] arr = Array.ConvertAll(input.Split(' '), int.Parse);
        Array.Sort(arr);
        return string.Join(" ", arr);        
    }
}

Your Main() then becomes:

public static void Main(string[] args)
{
    var input = Console.ReadLine();
    var output = InputConverter.ConvertInput(input);
    Console.WriteLine(output);
}

You can now test ConvertInput() without being dependent by the write and read functions of Console:

[TestMethod]
public void TwoNumbersDescendingAreSwapped()
{
    // Arrange
    var input = "2 1";
    var expectedOutput = "1 2"; 
    // Act
    var actualOutput = InputConverter.ConvertInput(input);
    // Assert
    Assert.AreEqual(expectedOutput, actualOutput);
}

As an aside: the way you are passing in your arguments seems as though you are guaranteeing that the input will always be what you expect it to be. What happens when the user passes in something totally different than string representations of integers? You need to validate the input in InputConverter.ConvertInput() and create appropriate courses of action based on that (throw an Exception, return null, depends on what you're after). You'll then have to unit test those scenarios as well to make sure ConvertInput() performs as expected for all cases.

like image 75
trashr0x Avatar answered Oct 25 '22 03:10

trashr0x