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