如何写unit testing的输出?

任何调用我的unit testingDebug.Write(line)Console.Write(Line)只是简单地跳过debugging时,输出从不打印。 从我正在使用的类中调用这些函数工作正常。

我明白,unit testing是为了自动化,但我仍然希望能够从unit testing中输出消息。

尝试使用TestContext.WriteLine()它在testing结果中输出文本。

例:

  [TestClass] public class UnitTest1 { private TestContext testContextInstance; /// <summary> /// Gets or sets the test context which provides /// information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } [TestMethod] public void TestMethod1() { TestContext.WriteLine("Message..."); } } 

这个“魔术”在MSDN中被描述为“testing框架自动设置属性,然后可以在unit testing中使用”。

谈话有点晚了。

我也试图让debugging或跟踪或控制台或TestContext工作在unit testing。

这些方法都不会在输出窗口中显示工作或显示输出。

  Trace.WriteLine("test trace"); Debug.WriteLine("test debug"); TestContext.WriteLine("test context"); Console.WriteLine("test console"); 

然后我注意到在我的testing结果窗口中,运行testing之后,在成功的绿色圆圈旁边还有另外一个图标,我点了一下就双击了。 这是我的testing结果,它包括以上所有types的笔记本。

我认为这仍然是实际的。

你可以使用这个NuGet包: https : //www.nuget.org/packages/Bitoxygen.Testing.Pane/

从这个库中调用自定义的WriteLine方法。
它在“输出”窗口中创build“testing”窗格,并始终将消息放在那里(在每次testing期间独立于DEBUG和TRACE标志)。

为了使跟踪更容易,我可以推荐创build基类:

 [TestClass] public abstract class BaseTest { #region Properties public TestContext TestContext { get; set; } public string Class { get { return this.TestContext.FullyQualifiedTestClassName; } } public string Method { get { return this.TestContext.TestName; } } #endregion #region Methods protected virtual void Trace(string message) { System.Diagnostics.Trace.WriteLine(message); Output.Testing.Trace.WriteLine(message); } #endregion } [TestClass] public class SomeTest : BaseTest { [TestMethod] public void SomeTest1() { this.Trace(string.Format("Yeah: {0} and {1}", this.Class, this.Method)); } } 

尝试使用:

Console.WriteLine()

debuggingDebug.WriteLine将只在定义DEBUG时进行。

其他的build议是使用: Trace.WriteLine ,但我没有尝试过。

还有一个选项(不知道VS2008是否有这个选项),但是在IDE中使用Test With Debugger选项运行testing时仍然可以使用Debug.WriteLine

你确定你在debugging中运行你的unit testing吗? Debug.WriteLine将不会在发布版本中被标注。

有两个选项可以尝试:

  • Trace.WriteLine(),它构buildinot发布版本以及debugging

  • 在unit testing的构build设置中未定义DEBUG

当我的testing/testing设置/默认处理器体系结构设置和我的testing项目引用的程序集不相同时,我得不到输出。 否则Trace.Writeline()工作正常。

我正在使用xunit,所以这就是我使用的: Debugger.Log(0, "1", input);

PS:你可以使用Debugger.Break(); 所以你可以看到你login

Trace.WriteLine应该工作,只要你select正确的输出(在输出窗口中find“显示输出来自”的下拉列表)

这取决于你的testing运行者…例如,我使用XUnit,所以万一这就是你正在使用,请按照下列指示:

https://xunit.github.io/docs/capturing-output.html

此方法将您的输出与每个特定的unit testing分组。


使用Xunit;
使用Xunit.Abstractions;

公共类MyTestClass
 {
    私有只读ITestOutputHelper输出;

    公共MyTestClass(ITestOutputHelper输出)
     {
         this.output =输出;
     }

     [事实]
     public void MyTest()
     {
         var temp =“我的class!”;
         output.WriteLine(“这是从{0}”,temp)的输出;
     }
 }

在我提供的用于写入输出窗口的链接中列出了另一种方法,但我更喜欢前面的方法。