views:

124

answers:

7

Hi everyone first post here.

I want to create a unit test for a member function of a class called ScoreBoard which is storing the TOP5 players in a simple game. The problem is that the method i am creating test for(SignInScoreBoard) is calling Console.ReadLine() so the User can type his name.

    public void SignInScoreBoard(int steps)
    {
        if (topScored.Count < 5)
        {
            Console.Write(ASK_FOR_NAME_MESSAGE);
            string name = Console.ReadLine();
            KeyValuePair<string, int> pair = new KeyValuePair<string, int>(name, steps);
            topScored.Insert(topScored.Count, pair);
        }
        else
        {
            if (steps < topScored[4].Value)
            {
                topScored.RemoveAt(4);
                Console.Write(ASK_FOR_NAME_MESSAGE);
                string name = Console.ReadLine();
                topScored.Insert(4, new KeyValuePair<string, int>(name, steps));
            }
        }
    }  

Is there a way to insert like 10 users so I can check if the 5 with less moves(steps) are being stored ?

+11  A: 

You'll need to refactor the lines of code that call Console.ReadLine into a separate object, so you can stub it out with your own implementation in your tests.

As a quick example, you could just make a class like so:

public class ConsoleNameRetriever {
     public virtual string GetNextName()
     {
         return Console.ReadLine();
     }
}

Then, in your method, refactor it to take an instance of this class instead. However, at test time, you could override this with a test implementation:

public class TestNameRetriever : ConsoleNameRetriever {
     // This should give you the idea...
     private string[] names = new string[] { "Foo", "Foo2", ... };
     private int index = 0;
     public override string GetNextName()
     {
         return names[index++];
     }
}

When you test, swap out the implementation with a test implementation.

Granted, I'd personally use a framework to make this easier, and use a clean interface instead of these implementations, but hopefully the above is enough to give you the right idea...

Reed Copsey
+1, oh yeah :-), always separate responsibilities.
Darin Dimitrov
I completely disagree. Refactoring just for the sake of testing is a bad idea. Check out Microsoft Moles for a much better solution.
Stephen Cleary
@Stephen Cleary There's no possible way for me to disagree with you more. Not only should you strive for testable code, but separation of concerns isn't just a testing concern. This refactoring will leave him with a more modular, reusable code base. It also enables him to write clean, simple unit tests.
Andy_Vulhop
@Stephen: I wouldn't refactor this "just for the sake of a test" - I'd refacotr this because it's got multiple responsibilities, and testability would be a simple side effect of the refactoring. This method is too complex to test effectively.
Reed Copsey
Separation of concerns is an excellent design goal, but too much just creates a huge mess. The unit tests aren't any cleaner or simpler than using Moles. The refactoring will *not* leave him with a more modular, reusable code base - simply because *code must be understood before it can be reused*, and the completely unnecessary abstraction of the console complicates the code considerably.
Stephen Cleary
@Stephen: I think we'll have to agree to disagree here. I feel that input of user data (and output, for that matter) should ALWAYS be abstracted out of methods. Having Console.ReadLine inside of a method that does anything but process user input smells really bad to me...
Reed Copsey
@Reed: I see what you're saying. I do agree that user interaction should be abstracted out, so in this situation I'd agree with you. But the suggested abstractions aren't clean at all; the only WPF implementation of `ConsoleNameRetriever` would force a modal dialog UI. I'm all for MVVM because of its UI semi-abstraction, but in this case, the only decent implementations would be `Console` or a test stub... That is why I see this as refactoring just for the sake of the test; the code really needs to be completely redesigned.
Stephen Cleary
+3  A: 

You should refactor your code to remove the dependency on the console from this code.

For instance, you could do this:

public interface IConsole
{
    void Write(string message);
    void WriteLine(string message);
    string ReadLine();
}

and then change your code like this:

public void SignInScoreBoard(int steps, IConsole console)
{
    ... just replace all references to Console with console
}

To run it in production, pass it an instance of this class:

public class ConsoleWrapper : IConsole
{
    public void Write(string message)
    {
        Console.Write(message);
    }

    public void WriteLine(string message)
    {
        Console.WriteLine(message);
    }

    public string ReadLine()
    {
        return Console.ReadLine();
    }
}

However, at test-time, use this:

public class ConsoleWrapper : IConsole
{
    public List<String> LinesToRead = new List<String>();

    public void Write(string message)
    {
    }

    public void WriteLine(string message)
    {
    }

    public string ReadLine()
    {
        string result = LinesToRead[0];
        LinesToRead.RemoveAt(0);
        return result;
    }
}

This makes your code easier to test.

Of course, if you want to check that the correct output is written as well, you need to add code to the write methods to gather the output, so that you can assert on it in your test code.

Lasse V. Karlsen
+1, IMO this is the structure you have to follow. However, I would think more abstractly, and instead of thinking about a Console and wrap it, I would use an INameProvider interface, with a GetName() method. Then, you can have implementations such as ConsoleNameProvider, HardCodedNameProvider, WhateverNameProvider, etc.
bloparod
+2  A: 

You can use Moles to replace Console.ReadLine with your own method without having to change your code at all (designing and implementing an abstract console, with support for dependency injection is all completely unnecessary).

Stephen Cleary
+1  A: 

Why not create a new stream (file/memory) for both stdin and stdout, then redirect input/ouput to your new streams before calling the method? You could then check the content of the streams after the method has finished.

OJ
By the way, I don't like this method at all :) I'd much prefer to abstract the console like others have suggested.
OJ
+1  A: 

Rather than abstracting Console, I would rather create a component to encapsulate this logic, and test this component, and use it in the console application.

Stephane
+1  A: 
public void SignInScoreBoard(int steps, Func<String> nameProvider)
{
    ...
        string name = nameProvider();
    ...
}  

In your test case, you can call it as

SignInScoreBoard(val, () => "TestName");

In your normal implementation, call it as

SignInScoreBoard(val, Console.ReadLine);

If you're using C# 4.0, you can make Console.ReadLine a default value by saying

public void SignInScoreBoard(int steps, Func<String> nameProvider=null)
{
    nameProvider = nameProvider ?? Console.ReadLine;
    ...
Mark H
A: 

I can't believe how many people have answered without looking at the question properly. The problem is the method in question does more than one thing i.e. asks for a name and inserts the top-score. Any reference to console can be taken out of this method and the name should be passed in instead:

public void SignInScoreBoard(int steps, string nameOfTopScorer)

For other tests you will probably want to abstract out the reading of the console output as suggested in the other answers.

Dan Ryan