我尝试Nunit测试一种方法,我声称我得到了正确的输出,但问题是每次代码跳转到:
Console.SetCursorPosition(xOffset,yOffset ++);
显然你无法重定向SetCursorPosition,所以我的问题是:.."无论如何,我可以合理地对这种方法进行单元测试"
public void Execute()
{
int xOffset = 84;
int yOffset = 3;
Console.SetCursorPosition(xOffset, yOffset++);
Console.WriteLine("Events");
string header = "| LogType | Message | tagCollection | Time |";
Console.SetCursorPosition(xOffset, yOffset++);
Console.WriteLine(header);
Console.SetCursorPosition(xOffset, yOffset++);
Console.WriteLine(new string('-', header.Length));
if (!string.IsNullOrWhiteSpace(Status))
{
Console.SetCursorPosition(xOffset, yOffset++);
Console.WriteLine(Status);
}
foreach (string str in NotificationList)
{
Console.SetCursorPosition(xOffset, yOffset++);
Console.WriteLine(str);
}
}
这是我的测试:
[Test]
public void NotificationDisplayer_inputTestString_ExpectedResult()
{
using (StringWriter sw = new StringWriter())
{
Console.SetOut(sw);
uutNotificationDisplayer.Execute();
Assert.That(sw.ToString()), Is.EqualTo(expectedResult));
}
}
答案 0 :(得分:0)
代码在一个地方做两件事导致问题。
您想在方法中构造一个字符串并打印它。他们应该分开。如果字符串构造正确或不正确,则测试用例感兴趣,而不是Console.WriteLine
或Console.SetCursorPosition
正常工作。因此,让我们将代码分开,如下所示。
static void Main(string[] args)
{
var messages = GetMessagesToPrint();
Execute(84, 3, messages);
}
// Method for which you should write the test method on its output
private static List<string> GetMessagesToPrint()
{
string header = "| LogType | Message | tagCollection | Time |";
...
...// actual list of string you want to construct.
...
var messages = new List<string> {"Events", header, new string('-', header.Length)};
return messages;
}
//This doesnt need a test method
public static void Execute(int xOffset, int yOffset, IEnumerable<string> messageToPrint)
{
foreach (var message in messageToPrint)
{
Console.SetCursorPosition(xOffset, yOffset++);
Console.WriteLine(message);
}
}
然后,您可以为GetMessagesToPrint编写单元测试,无需担心System.Console方法。