Skip to content

Instantly share code, notes, and snippets.

@asierba
Last active January 19, 2024 11:12
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save asierba/ad9978c8b548f3fcef40 to your computer and use it in GitHub Desktop.
Save asierba/ad9978c8b548f3fcef40 to your computer and use it in GitHub Desktop.
How to mock console in unit tests
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("What's your name?");
var name = Console.ReadLine();
Console.WriteLine(string.Format("Hello {0}!!", name));
}
[Test]
public void something()
{
var output = new StringWriter();
Console.SetOut(output);
var input = new StringReader("Somebody");
Console.SetIn(input);
Program.Main(new string[] { });
Assert.That(output.ToString(), Is.EqualTo(string.Format("What's your name?{0}Hello Somebody!!{0}", Environment.NewLine)));
}
}
@codingedgar
Copy link

Thanks!

@asierba
Copy link
Author

asierba commented Feb 21, 2020

👍

@tribhuwansingh
Copy link

Thanks , good example.

@younusrahman87
Copy link

many many thanks

@younusrahman87
Copy link

how can take multi input??
if i have a one method and take multi console.readline().

please ans

@asierba
Copy link
Author

asierba commented Dec 7, 2020

how can take multi input??
if i have a one method and take multi console.readline().

please ans

Every input will be part of the Console Input separated with a new line.
I've created another gist with multiple inputs to see this clearly: https://gist.github.com/asierba/3f51a7b82011bd171299fae307580cd8

@Ninza-viren
Copy link

How do we read numbers?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment