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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With