NUnit Test - Looping - C#

假如想象 提交于 2019-12-11 05:15:36

问题


I am new to TDD and trying to solve a problem.

In my task, I have to read a bunch of strings from console and add them to a list of string type. In my test method, I have written a for loop to read strings and passing to a method to add. I don't know how to test this process, a bit confused. Any help will be appreciated. Thanks.

Loop in the test method.

   for(int i=0;i<robot.noOfCommands;i++)
        {
            robot.readCommand(Console.ReadLine());

        } 

I am writing code in C#.Net


回答1:


Unit tests should never require human interaction, so using Console.ReadLine() is a major no-no.

What you probably want, is to feed your robot object with some predefined input. Then you can test (Assert), that the outcome is what you expect. That is the essence of unit testing.




回答2:


In order for your test to work, you need to fake dependency on external service, which in this case is System.Console. Method you want to test (or class) need to have the ability to be provided with different types of this dependency - so that faked one can work too.

With Console.ReadLine what you really need is TextReader. Your looping method could look like this:

public void MyMethod(TextReader reader)
{
    for (int i = 0; i < robot.noOfCommands; i++)
    {
        robot.readCommand(reader.ReadLine());
    }
}

In real application, you will call it with MyMethod(Console.In). In test, you can prepare fake reader (eg. reading from resource file) with predefined commands.



来源:https://stackoverflow.com/questions/8961655/nunit-test-looping-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!