gpt4 book ai didi

c# - 称为抑制 Debug.WriteLine 和 Trace.WriteLine 的单元测试代码

转载 作者:行者123 更新时间:2023-11-30 16:25:39 26 4
gpt4 key购买 nike

我有一些代码需要在运行测试时查看,并且TestContext 必须是我的测试类的一部分我需要显示正在测试的类的 debug.writelines。我考虑过只是将 TestContext 传递给我的 MessageStatus 静态方法,并且可能必须,但那将是一个 PITA,因为 UnitTest 类会有将 TestContext 传递给它正在测试的对象。太紧结合我的口味。

基本情况

 [TestMethod]
public void TestA()
{
//....
Assert.IsTrue(Blah.Blah()));
}



public void Blah()
{
Debug.WriteLine("Hello");
}

在我运行单元测试时从未出现!

我可以把它改成:

TestContext t;
[TestMethod]
public void TestA()
{
//....
Assert.IsTrue(Blah.Blah(t)));
}



public void Blah(TestContext p1)
{
p1.WriteLine("Hello");
}

但这太疯狂了,它意味着更改我所有的签名和紧密耦合。我在 How to write output from a unit test? 阅读了帖子它没有帮助:(

最佳答案

如果您需要查看由 Debug.WriteLine 生成的行或处理由 Debug.Assert 生成的断言,您可以创建自己的 System.Diagnostic.TraceListener 以将输出重定向到 TestContext - 请参阅我的回答 What do I have to do so that assertions won't block automated tests anymore? .

public class MyListenerThatDoesNotShowDialogOnFail: 
System.Diagnostics.TraceListener
{
// This is to avoid message box on Debug.Assert(false);
public override void Fail(string message, string detailMessage)
{// do something UnitTest friendly here like Assert.Fail(false)
}

// This (+Write) is to redirect Debug.WriteLine("Some trace text");
public override void WriteLine(string message)
{// do something UnitTest friendly here like TestContext.Write(message)
}
}

测试设置监听器中的某处。请注意,下面的示例是经过简化的,您可能希望保存当前的监听器并在测试结束时恢复。

Debug.Listeners.Clear();
Debug.Listeners.Add(new MyListenerThatDoesNotShowDialogOnFail());

关于c# - 称为抑制 Debug.WriteLine 和 Trace.WriteLine 的单元测试代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9642171/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com