MSTest:从Assert获取输出消息



我正在使用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");
}

我会得到

消息:Assert.AreEqual失败。应为true。变错了。此错误消息也应显示在日志中。

在我的日志文件中。

我试着做

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();
}

但是CCD_ 1返回空字符串。

如何从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 failed. Expected:<False>. Actual:<True>. test message

最新更新