Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MSTest: Get output message from Assert?

I'm writing integration tests using the MSTest framework. The tests and code under test all have significant logging built into them.

I'm trying to figure out a way to hook into the Assert's output so I can write it to the log files along with the rest of log.

For example, if I have a test method like

[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 true. Got false. This error message should also appear in the log.

in my log file.

I tried doing

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 the testOutputBuilder returns an empty string.

How can I grab the string outputs from the assert methods in MSTest?

like image 875
CHendrix Avatar asked Mar 24 '16 13:03

CHendrix


2 Answers

I wrote a workaround using separate function:

public string WriteErrorToFile(TextWriter textwriter, string errorMessage)
{
        textwriter.WriteLine(errorMessage);
        return errorMessage;
}

and code inside test should be modified like:

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

If you have only one log file then you can remove first parameter to the function.

Hope this helps

like image 115
Ales Avatar answered Oct 10 '22 09:10

Ales


I did this:

public void OutputAssert(Action func)
    {
        try
        {
            func();
        }
        catch (Exception ex)
        {
            OutputToFile(ex.Message);
            throw ex;
        }            
    }

And then in the test:

[TestMethod]        
public void TestAssertOutput()
    {
        OutputAssert(() => Assert.AreEqual(false, true, "test message"));
    }

The output being:

Assert.AreEqual failed. Expected:<False>. Actual:<True>. test message
like image 2
Cradent Avatar answered Oct 10 '22 10:10

Cradent