Прежде всего, перепишите ваш метод, чтобы он мог быть проверен модулем и не полагался на ввод и вывод консоли, например,
public class ChoiceOption
{
private readonly Func<string> readLine;
private readonly Action<string> writeLine;
public ChoiceOption(Func<string> readLine, Action<string> writeLine)
{
this.readLine = readLine;
this.writeLine = writeLine;
}
public int Choice(string message, string errorMessage)
{
while (true)
{
writeLine(message);
string userInput = readLine();
if (string.IsNullOrEmpty(userInput)) return 0;
if (int.TryParse(userInput, out int result))
{
return result;
}
writeLine(errorMessage);
}
}
}
Теперь вы можете вводить методы для чтения и записи, которые вводят данные теста и собрать вывод, чтобы проверить это. Взгляните на пакет nuget Moq
также как способ создания этих фиктивных объектов для тестирования.
[TestFixture]
public class TestMethod
{
[TestCase("", ExpectedResult = "Message\n0")]
[TestCase("123", ExpectedResult = "Message\n123")]
[TestCase("A\n1234", ExpectedResult = "Message\nError\nMessage\n1234")]
public string MethodReturnsExpected(string input)
{
// Create mock objects for testing that simulate user input
int readPos = 0;
string output = "";
Func<string> readline = () => input.Split('\n')[readPos++];
Action<string> writeline = (line) => output = output + line + "\n";
// Create the 'unit under test'
var uut = new ChoiceOption(readline, writeline);
int result = uut.Choice("Message", "Error");
// Return something that can be verified
return output + result;
}
}