开发者

C# unit test for a method which calls Console.ReadLine()

I want to create a unit test for a member function of a class called ScoreBoard which is storing the top five players in a game.

The problem is that the method I created a test for (SignInScoreBoard) is calling Console.ReadLine() so the user can type their 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 ten users so I can check if the five with less moves (steps) are being stored?


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...


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.


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


You should not mock something that comes from the framework, .NET already provides abstractions for its components. For the console, they are the methods Console.SetIn() and Console.SetOut().

For instance, with regards to Console.Readline(), you would do it this way:

[TestMethod]
MyTestMethod()
{
    Console.SetIn(new StringReader("fakeInput"));
    var result = MyTestedMethod();
    StringAssert.Equals("fakeInput", result);
}

Considering the tested method returns the input read by Console.Readline(). The method would consume the string we set as input for the console and not wait for interactive input.


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.


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


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.


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.


I had a similar issue few days ago. Encapsulation Console class seemed like overkill for me. Based on KISS principle and IoC/DI principle I putted dependencies for writer (output) and reader (input) to constructor. Let me show the example.

We can assume simple confirmation provider defined by interface IConfirmationProvider

public interface IConfirmationProvider
{
    bool Confirm(string operation);
}

and his implementation is

public class ConfirmationProvider : IConfirmationProvider
{
    private readonly TextReader input;
    private readonly TextWriter output;

    public ConfirmationProvider() : this(Console.In, Console.Out)
    {

    }

    public ConfirmationProvider(TextReader input, TextWriter output)
    {
        this.input = input;
        this.output = output;
    }

    public bool Confirm(string operation)
    {
        output.WriteLine($"Confirmed operation {operation}...");
        if (input.ReadLine().Trim().ToLower() != "y")
        {
            output.WriteLine("Aborted!");
            return false;
        }

        output.WriteLine("Confirmated!");
        return true;
    }
}

Now you can easily test your implementation when you inject dependency to your TextWriter and TextReader (in this example StreamReader as TextReader)

[Test()]
public void Confirm_Yes_Test()
{
    var cp = new ConfirmationProvider(new StringReader("y"), Console.Out);
    Assert.IsTrue(cp.Confirm("operation"));
}

[Test()]
public void Confirm_No_Test()
{
    var cp = new ConfirmationProvider(new StringReader("n"), Console.Out);
    Assert.IsFalse(cp.Confirm("operation"));
}

And use your implementation from apllication standard way with defaults (Console.In as TextReader and Console.Out as TextWriter)

IConfirmationProvider cp = new ConfirmationProvider();

That's all - one additional ctor with fields initialization.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜