MSTest:从Assert获取输出消息?

CHe*_*rix 6 c# console logging mstest

我正在使用MSTest框架编写集成测试.测试中的测试和代码都内置了重要的日志记录.

我试图找出一种方法来挂钩Assert的输出,这样我就可以将它与日志的其余部分一起写入日志文件.

例如,如果我有一个类似的测试方法

[TestMethod]
SomeRandomIntegrationTest()
{
  //Code to actually run the test, and includes logging.

  Assert.AreEqual(true, false, "This error message should also appear in the log");
}
Run Code Online (Sandbox Code Playgroud)

我会的

消息: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();
}
Run Code Online (Sandbox Code Playgroud)

但是testOutputBuilder返回一个空字符串.

如何从MSTest中的断言方法中获取字符串输出?

小智 2

我使用单独的函数编写了一个解决方法:

public string WriteErrorToFile(TextWriter textwriter, string errorMessage)
{
        textwriter.WriteLine(errorMessage);
        return errorMessage;
}
Run Code Online (Sandbox Code Playgroud)

测试内的代码应修改为:

Assert.AreEqual(true, false, WriteErrorToFile(originalWriter, "This error message should also appear in the log"));
Run Code Online (Sandbox Code Playgroud)

如果您只有一个日志文件,那么您可以删除该函数的第一个参数。

希望这可以帮助