C#单元测试为其调用到Console.ReadLine()的方法 [英] c# Unit Test for a method which is calling Console.ReadLine()

查看:275
本文介绍了C#单元测试为其调用到Console.ReadLine()的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好第一篇文章在这里。

Hi everyone first post here.

我要为所谓的记分板被存储在一个简单的游戏TOP5球员类的成员函数创建单元测试。
的问题是,我对(SignInScoreBoard)创建测试方法是调用到Console.ReadLine(),以便用户可以输入自己的名字。

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



有插入的方式像10个用户,所以我可以检查,如果5用更少的移动(步)被存储?

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

推荐答案

您将需要重构的代码调用到Console.ReadLine成一个单独的对象的线条,这样你就可以存根它。出在你的测试您自己的实现。

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

这篇关于C#单元测试为其调用到Console.ReadLine()的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆