How to unit test "console.readLine" for invalid input?
.net, c#, visual-studio-2010
Solution
Just like the two comments posted. I would consider refactoring your code to look something more like
string input = Console.ReadLine();
try
{
int PhoneIMEINumber = parse_input(input);
}
catch(Exception)
{
return null;
}
and then you'd have a function
public int parse_input(string input)
{
return int.Parse(input);
}
THEN you'd write a unit test for the `parse_input` function. The example code seems quite trivial though and it is hard to justify writing a unit test around a wrapper function for int.Parse(), but I'm assuming that your parsing might get more complicated in the future.
Problem
I am scratching my head on this little problem. I have this line and 3 other similar ones in a method ``` try { int PhoneIMEINumber = int.Parse(Console.ReadLine()); } { catch(Exception) { return null; } ``` If the user enters "abcd" for input, this throws an exception and I can catch it and show an error message. But how do I make a unit test for this? I can't simulate console input from the unit test ofcourse and I want to check from my unit test if a null was returned. Thank you