I'm having trouble figuring out how to unit test a function. It's used for getting user input password-style, so that asterisks appear instead of what the user has typed. So I'm trying to capture console I/O to compare it to the expected values.
This is the function:
public string getMaskedInput(string prompt)
{
string pwd = "";
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
pwd = pwd += key.KeyChar;
Console.Write("*");
}
else
{
if (key.Key == ConsoleKey.Backspace && pwd.Length > 0)
{
pwd = pwd.Substring(0, pwd.Length - 1);
Console.Write("\b \b");
}
}
}
while (key.Key != ConsoleKey.Enter);
return pwd;
}
And the test:
public void getInputTest()
{
//arrange
var sr = new StringReader("a secret");
var sw = new StringWriter();
Console.SetOut(sw);
Console.SetIn(sr);
Input i = new Input();
string prompt="what are you typing? ";
//act
string result = i.getMaskedInput(prompt);
//assert
var writeResult = sw.ToString();
Assert.IsTrue((writeResult == "what are you typing? ")&&(result=="a secret"));
EDIT: I rechecked my unit test and it had a bug in it; now that I've fixed it, the test just hangs. Stepping through the test indicates that it has something to do with Console.ReadKey()
, which I suspect can't be redirected with StreamReader()
the way ReadLine()
can.
Also, this seems to be two asserts in the same test, is that the right way to test this function?