MSTest: Get output message from Assert?

I am writing integration tests using the MSTest framework. Tests and test code have a significant log built into them.

I am trying to find a way to connect to the Assert output so that I can write it to the log files along with the rest of the log.

For example, if I have a testing method, for example

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

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

I would get

Message: Assert.AreEqual failed. Expected. Got a lie. This error message should also appear in the log.

in my log file.

I tried to do

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

but testOutputBuilderreturns an empty string.

How can I capture string output from assert methods in MSTest?

+4
source share
2 answers

:

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"));

, .

,

+1

:

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
+1

All Articles