Arun Kumar
Arun Kumar

Reputation: 59

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          
}

Upvotes: 0

Views: 393

Answers (2)

mm8
mm8

Reputation: 169400

You could add a TextWriter argument to your method and use this one to write:

public int PrintData(int[] input, int n, TextWriter sw)
{
    ...
    sw.WriteLine(input[i]);
}

When you call the method, you could then supply any TextWriter, including Console.Out or a stub:

PrintData(new int[0], 0, Console.Out); //writes to the console

//in unit test:
TextWriter tw = new StringWriter();
PrintData(new int[0], 0, tw); //writes to tw
Assert.AreEqual("...", tw.ToString());

Upvotes: 0

Mighty Badaboom
Mighty Badaboom

Reputation: 6155

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

Upvotes: 1

Related Questions