Reputation: 1095
I am writing a program in a C# Console Application and within some of the methods I have Console.ReadLine() and Console.WriteLine(). I want to know how to give the input within a Test Case.
Example:
Console.WriteLine("Enter account number: ");
accountNumber = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter name: ");
cStringName = Convert.ToString(Console.ReadLine());
name = cStringName;
Console.WriteLine("Enter balance: ");
balance = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter Date: ");
dateCreated = Convert.ToString(Console.ReadLine());
So basically the method returns a bool saying if an account was created or not. In my test case I want to be able to call this method but in order for it to execute I need to set accountNumber, name, balance, and date. Is there some sort of way of doing this? Or is the best way just to add parameter to the method(which i prefer not to do)?
Upvotes: 1
Views: 296
Reputation: 69250
Rewrite the method so that it takes a couple of Stream
as parameters. Then when you call it in the real program, send in Console.Out
and Console.In
as parameters. When calling from your test case, send in some memory streams instead.
When writing this kind of methods and you want to test them, they should not depend directly on the console, but rather on an abstract stream. Then you use dependency injection (e.g. passing in the streams as parameters) to be able to substitute the console for a memory stream when testing.
Upvotes: 3