Search code examples
c#mstest

How to write MS Unit Test for the code having console.writeline


I'm using bubble sort for sort a array in descending order and print the output in console.writeline method, now i'm confused how to write a unit test to test against the console.writeline

//Console Application Code
public int PrintData(int[] input, int n)
{
    for (int i = 0; i < n; i++)
    {
        if (input[i] <= 0)
        {
            status = -2;
        }
        else
        {
            for (int j = i + 1; j < n; j++)
            {
                if (input[i] < input[j])
                {
                    int temp = input[i];
                    input[i] = input[j];
                    input[j] = temp;
                }
            }
        }
    }

    for (int i = 0; i < n; i++)
    {
        Console.WriteLine(input[i]); //How to check this output in MSTest
    }
}

//MS Test Code
[TestMethod]        
public void ArrayDisplayingInDescendingOrder()
{
    int[] arr = new int[5] { 3, 2, 1, 4, 5 };
    int[] expected = { 5, 4, 3, 2, 1 };            
    array.PrintData(arr, 5); 
    //What i should do here          
}

Solution

  • If you really want to test the Concole.WriteLine calls I would create a class with an interface to encapsulate the Console.WriteLine. Could look like this.

    public class ConsoleService : IConsoleService
    {
        public void WriteToConsole(string text)
        {
            Console.WriteLine(text);
        }
    }
    

    Then you can use this service in your PrintData method and mock the calls in your test and verify the calls; for example with Moq.

    Easier would be to return a List from PrintData and add each entry to the list instead of Console.WriteLine(input[i]); because then you can test if the correct values where added. And in your application you simply can print all entries with a for each loop.

    So you have to change your code to make it testable. But your code would be cleaner after this (I would hardly recommend not to use any UI interaction in logic classes). Good example on how tests can make code cleaner, too ;)