Eddie Parker
Eddie Parker

Reputation: 4888

VS2015: TraceSource Output in Test Explorer?

I've got a library that I'm trying to unit test. I use TraceSource to write out warning details, and as I have the unit tests set to run as part of the build, I'd like them to show up when the tests are run - particularly on failure.

I've tried the following code to register a trace listener, but my WriteLine stuff never gets called, despite the constructor being called. See code at the bottom [1].

How do I get my traces to show up as part of the test runner?

[1] Code for my testcontexttracelistener:

[TestClass]
public class TestContextTraceListener : TraceListener
{
    TestContext testContext;

    public TestContextTraceListener(TestContext testContext)
    {
        this.testContext = testContext;
    }

    public override void Write(string message)
    {
        // EP TODO: This is likely going to create newlines where they shouldn't be, but testContext doesn't have a .Write, and I'm too lazy to buffer.
        this.WriteLine(message); 
    }

    public override void WriteLine(string message)
    {
        this.testContext.WriteLine(message);
    }
}

[TestClass]
public class TestAssemblyInitializeAndCleanup
{
    static TraceListener traceListener;

    [AssemblyInitialize]
    public static void OnInitialize(TestContext testContext)
    {
        if (traceListener == null)
        {
            // This code is reached, but the listener never gets triggered.
            traceListener = new TestContextTraceListener(testContext);
            Trace.Listeners.Add(traceListener);
        }
    }

    [AssemblyCleanup]
    public static void OnCleanup()
    {
        Cleanup();
    }

    static void Cleanup()
    {
        if (traceListener != null)
        {
            traceListener.Flush();
            Trace.Listeners.Remove(traceListener);
            traceListener.Dispose();
        }
    }
}

Upvotes: 2

Views: 210

Answers (0)

Related Questions