我只是想让我的代码出于逻辑目的进行审查。我认为它的工作方式符合我的预期,但我想与更精通 C# 的同行再次确认。
所以在这里我正在测试一个验证用户输入的控制台应用程序。我正在使用 StringReader 来模拟用户响应。所以我输入 5 作为我的回复,如果我的回复不是有效的浮点数,那么我应该收到一个错误。
我针对非浮点值对此进行了测试,我的 for 循环导致我输入了内存不足异常,这是有道理的。但出于某种原因,在我的测试中,我觉得我正在写我的 Input1() 函数并且只是验证我的输入确实是我模拟的值?还是我的测试实际上验证了 Input1() 的返回值实际上是浮点数形式的 num1 - 从而通过了我的验证?
对不起,如果这是矫枉过正并且没有意义。
public float Input1()
{
//Console.WriteLine("Type a number, and then press Enter");
bool Valid = false;
while (Valid == false)
{
//bad implementation here: Input = Input;
String Input = Console.ReadLine();
Console.WriteLine(Input);
if (!float.TryParse(Input, out Number))
{
Console.WriteLine("Not an integer, please try again.");
}
else
{
Valid = true;
num1 = (float)Convert.ToDecimal(Input);
}
}
return num1;
}
[Test]
public void Test2()
{
var calc = new CalculatorApp.Program();
var output = new StringWriter();
float num1;
float expectedresult;
Console.SetOut(output);
var input = new StringReader("5");
Console.SetIn(input);
calc.Input1();
//num1 = (float)Convert.ToDecimal(output);
Assert.That(output.ToString(), Is.EqualTo(string.Format("5\r\n", Environment.NewLine)));
GC.Collect();
}