在单元测试中,如果我们要测试一个函数:
T TestFunc(arg1,arg2,……)
{
//函数主体
}
我们可以给出特定的参数,然后使用:
Assert.AreEqual(expectedAns,Testfunc())
判断是否成功,面对没有返回值得函数,要怎么测试呢?
我们可以很容易的在测试函数中临时插入Console 语句,然后在测试函数中检测Console输出的字符串是不是我们所预料的:
[TestMethod]
public void ValidateConsoleOutput()
{
using (StringWriter sw = new StringWriter())
{
Console.SetOut(sw);
ConsoleUser cu = new ConsoleUser();
cu.DoWork();
string expected = string.Format("Ploeh{0}", Environment.NewLine);
Assert.AreEqual<string>(expected, sw.ToString());
}
}
sw会获取Console所有的字符串,所以有多个输出,你可以使用string.Contain("expected")来判断是否包含你预设的结果。