C# MSTest:从断言获取输出消息?
我正在使用MSTest框架编写集成测试。测试和测试中的代码都内置了重要的日志记录 我正试图找出一种方法来钩住断言的输出,以便将其与日志的其余部分一起写入日志文件 例如,如果我有一个测试方法,比如C# MSTest:从断言获取输出消息?,c#,logging,console,mstest,C#,Logging,Console,Mstest,我正在使用MSTest框架编写集成测试。测试和测试中的代码都内置了重要的日志记录 我正试图找出一种方法来钩住断言的输出,以便将其与日志的其余部分一起写入日志文件 例如,如果我有一个测试方法,比如 [TestMethod] SomeRandomIntegrationTest() { //Code to actually run the test, and includes logging. Assert.AreEqual(true, false, "This error message
[TestMethod]
SomeRandomIntegrationTest()
{
//Code to actually run the test, and includes logging.
Assert.AreEqual(true, false, "This error message should also appear in the log");
}
我会得到
消息:Assert.AreEqual失败。希望是真的。这是假的。此错误消息也应出现在日志中
在我的日志文件中
我试过了
private StringBuilder testOutputBuilder;
private StringWriter testOutputWriter;
private TextWriter originalWriter;
[TestInitialize]
public virtual void Initialize()
{
//Redirect the test output into the log files
testOutputBuilder = new StringBuilder();
testOutputWriter = new StringWriter(testOutputBuilder);
originalWriter = Console.Out;
Console.SetOut(testOutputWriter);
}
[TestCleanup]
public virtual void TestCleanup()
{
if (TestContext.CurrentTestOutcome != UnitTestOutcome.Passed)
{
//File logging happens here using the testOutputBuilder
}
Console.SetOut(originalWriter);
testOutputWriter.Dispose();
}
但是testOutputBuilder
返回一个空字符串
如何从MSTest中的assert方法获取字符串输出?我使用单独的函数编写了一个解决方案:
public string WriteErrorToFile(TextWriter textwriter, string errorMessage)
{
textwriter.WriteLine(errorMessage);
return errorMessage;
}
内部测试的代码应该修改如下:
Assert.AreEqual(true, false, WriteErrorToFile(originalWriter, "This error message should also appear in the log"));
如果只有一个日志文件,则可以删除函数的第一个参数
希望这有帮助我做到了:
public void OutputAssert(Action func)
{
try
{
func();
}
catch (Exception ex)
{
OutputToFile(ex.Message);
throw ex;
}
}
然后在测试中:
[TestMethod]
public void TestAssertOutput()
{
OutputAssert(() => Assert.AreEqual(false, true, "test message"));
}
输出为:
Assert.AreEqual失败。预期:。实际值:。测试消息
断言抛出异常,这些异常通过
控制台显示。错误。我自己不使用mtest。但我认为,如果将Console.Error
循环到steam中,您应该会看到弹出的断言消息。@NickOtten尝试使用Console.SetError(testOutputWriter)
。没有骰子。
Assert.AreEqual failed. Expected:<False>. Actual:<True>. test message