I'm trying to figure out a good way to log messages to the console / test explorer / pipeline execution logs when running my MSTest Test Project.
I've noticed that you can either write the output to the console using the usual suspect:
Console.WriteLine("Your text here");
But you can also do it from TestContext object, for example:
TestContext _testContext;
_testContext.WriteLine("TEST CONTEXT : This is a test message");
The achieved result ends up in the same place (in the various logs) and also within the .trx
file, under the "StdOut" messages:
<UnitTestResult >
<Output>
<StdOut>
TestInitialize
Test Name : AssertIsTrue
TestCleanup
TestContext Messages:
TEST CONTEXT : This is a test message
</StdOut>
</Output>
</UnitTestResult>
So I'm wondering what is the best / more sustainable course of action to enable proper "logging" within the various tests ?
(OR maybe I'm doing it totally wrong, and there is a good way to do it using a Logger or equivalent).
An implementation of TestContext.WriteLine
(the method is abstract) will most likely call Trace.WriteLine
to have then all their TraceListeners
write, store, output, email or queue the string.
That the console output ends up in the trx is more of a convenience I suspect in case that the test runner itself fails catastrophically.
Tracing and diagnostic output should always be written by means of the System.Diagnostics.Trace
or System.Diagnostics.Debug
class or implementations that use the same. If output of these is needed on the console, register the ConsoleTraceListener
.
That might make it easier in test case scenario's to determine that Console.WriteLine
come from the Subject Under Test, not your unit test code.
This is under the assumption that the testrunner doesn't pile everything in one bag anyway.