1

我有一个正在尝试进行单元测试的库。我使用 TraceSource 写出警告详细信息,并且由于我将单元测试设置为作为构建的一部分运行,所以我希望它们在测试运行时出现 - 特别是在失败时。

我已尝试使用以下代码注册跟踪侦听器,但我的 WriteLine 内容从未被调用,尽管调用了构造函数。请参阅底部的代码 [1]。

如何让我的痕迹显示为测试运行器的一部分?

[1] 我的 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();
        }
    }
}
4

0 回答 0