如何编写单元测试的输出?

发布于 2024-10-13 09:34:57 字数 144 浏览 6 评论 0原文

我的单元测试中对 Debug.Write(line) 或 Console.Write(Line) 的任何调用在调试时都会被跳过,并且永远不会打印输出。从我正在使用的类中调用这些函数工作正常。

我知道单元测试应该是自动化的,但我仍然希望能够从单元测试中输出消息。

Any call in my unit tests to either Debug.Write(line) or Console.Write(Line) simply gets skipped over while debugging and the output is never printed. Calls to these functions from within classes I'm using work fine.

I understand that unit testing is meant to be automated, but I still would like to be able to output messages from a unit test.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

尘世孤行 2024-10-20 09:34:58

正如 @jonzim 提到的,这确实取决于测试运行者。
对于 NUnit 3,我必须使用 NUnit.Framework.TestContext.Progress.WriteLine() 在 Visual Studio 2017 的输出窗口中获取运行输出。NUnit

描述了如何:此处

据我了解,这围绕着测试运行者收到的测试执行的附加并行化。

It is indeed depending on the test runner as @jonzim mentioned.
For NUnit 3 I had to use NUnit.Framework.TestContext.Progress.WriteLine() to get running output in the Output window of Visual Studio 2017.

NUnit describes how to: here

To my understanding this revolves around the added parallelization of test execution the test runners have received.

想念有你 2024-10-20 09:34:58

我觉得还是很实际的。

您可以使用此 NuGet 包:Bitoxygen.Testing.Pane

从此库中调用自定义WriteLine方法。
它在输出窗口内创建一个测试窗格,并始终将消息放在那里(在每次测试期间,它独立于DEBUG和TRACE标志运行)。

为了使跟踪更容易,我建议创建一个基类:

[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));
    }
}

I think it is still actual.

You can use this NuGet package: Bitoxygen.Testing.Pane

Call the custom WriteLine method from this library.
It creates a Testing pane inside the Output window and puts messages there always (during each test, it runs independently of DEBUG and TRACE flags).

To make tracing more easy I can recommend to create a base class:

[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));
    }
}
波浪屿的海角声 2024-10-20 09:34:58

我正在使用 xUnit 所以这就是我使用的:

Debugger.Log(0, "1", input);

PS:你可以使用 Debugger.Break(); 也是如此,这样您就可以在 out 中看到您的日志。

I'm using xUnit so this is what I use:

Debugger.Log(0, "1", input);

PS: you can use Debugger.Break(); too, so you can see your log in out.

苹果你个爱泡泡 2024-10-20 09:34:58

我偶然发现 DebugView (启用了 Capture > 捕获 Win32 选项)将捕获对 System.Console 的写入。

示例测试:

[Test]
public void FooTest()
{
    for (int i = 0; i < 5; i++)
        Console.WriteLine($"[{DateTime.UtcNow.ToString("G")}] Hello World");
}

“在此处输入图像描述"

I've accidentally found that DebugView (with enabled Capture > Capture Win32 option) will capture writes to System.Console.

Example test:

[Test]
public void FooTest()
{
    for (int i = 0; i < 5; i++)
        Console.WriteLine(
quot;[{DateTime.UtcNow.ToString("G")}] Hello World");
}

enter image description here

微凉 2024-10-20 09:34:58

如果您使用 dotnet test 运行测试,您可能会发现 Console.Error.WriteLine 会生成输出。

这就是我使用 NUnit 测试解决该问题的方法,该测试似乎也抑制了所有调试、跟踪和标准输出。

If you're running tests with dotnet test, you may find that Console.Error.WriteLine produces output.

This is how I've worked around the issue with NUnit tests, which also seem to have all Debug, Trace and standard output suppressed.

墟烟 2024-10-20 09:34:58

对于测试资源管理器中的 VS2022,输出将显示在测试详细信息摘要窗格中。此外,您可以右键单击您的测试并选择“打开测试日志”或简单地按 Control+L,然后将打开一个测试日志,其中包含您的所有 Debug.WriteLine 注释。

此外,当 .runsettings 附加到单元测试时,请确保CaptureTraceOutput设置为True

<CaptureTraceOutput>True</CaptureTraceOutput>

DateTime myExpectedDateTime = sortedLPR[0].myDateTime;
DateTime myPreviousDateTime = sortedLPR[0].myDateTime;      // 1st date element
Debug.WriteLine($"(1) myPreviousDateTime: {myPreviousDateTime}");
Console.WriteLine($"(2) myPreviousDateTime: {myPreviousDateTime}");

testlog

请注意输出的顺序:(2) before (1) - 标准输出在调试输出之前。

For VS2022 in the Test Explorer the output will show up in the Test Detail Summary Pane. In additional you can right-click on your test and choose the 'Open test log' or simply Control+L and a testlog will open with all your Debug.WriteLine comments.

Further when .runsettings was attached to the unit test, please ensure that the CaptureTraceOutput was set to True.

<CaptureTraceOutput>True</CaptureTraceOutput>

DateTime myExpectedDateTime = sortedLPR[0].myDateTime;
DateTime myPreviousDateTime = sortedLPR[0].myDateTime;      // 1st date element
Debug.WriteLine(
quot;(1) myPreviousDateTime: {myPreviousDateTime}");
Console.WriteLine(
quot;(2) myPreviousDateTime: {myPreviousDateTime}");

testlog

Please notice the order of the output: (2) before (1) - standard output before debug output.

垂暮老矣 2024-10-20 09:34:58

尝试使用:

Console.WriteLine()

Debug.WriteLine 的调用仅在定义 DEBUG 期间进行。

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

还有一个选项(不确定 Visual Studio 2008 是否有),但当您使用 Test With Debugger 选项运行测试时,您仍然可以使用 Debug.WriteLine在 IDE 中。

Try using:

Console.WriteLine()

The call to Debug.WriteLine will only be made during when DEBUG is defined.

Other suggestions are to use: Trace.WriteLine as well, but I haven't tried this.

There is also an option (not sure if Visual Studio 2008 has it), but you can still Use Debug.WriteLine when you run the test with Test With Debuggeroption in the IDE.

暮年慕年 2024-10-20 09:34:58

通过以下示例解决:

public void CheckConsoleOutput()
{
    Console.WriteLine("Hello, World!");
    Trace.WriteLine("Trace Trace the World");
    Debug.WriteLine("Debug Debug World");
    Assert.IsTrue(true);
}

运行此测试后,在“测试通过”下,可以选择查看输出,这将打开输出窗口。

Solved with the following example:

public void CheckConsoleOutput()
{
    Console.WriteLine("Hello, World!");
    Trace.WriteLine("Trace Trace the World");
    Debug.WriteLine("Debug Debug World");
    Assert.IsTrue(true);
}

After running this test, under 'Test Passed', there is the option to view the output, which will bring up the output window.

悲凉≈ 2024-10-20 09:34:58

您确定正在调试中运行单元测试吗? Debug.WriteLine 在发布版本中不会被调用。

可以尝试的两个选项是:

  • Trace.WriteLine(),它内置于发布版本和调试中

  • 在单元测试的构建设置中取消定义 DEBUG

Are you sure you're running your unit tests in Debug? Debug.WriteLine won't be called in Release builds.

Two options to try are:

  • Trace.WriteLine(), which is built into release builds as well as debug

  • Undefine DEBUG in your build settings for the unit test

真心难拥有 2024-10-20 09:34:58

原因/解决方案的不同变体:

我的问题是我没有得到输出,因为我正在异步上下文中循环地将异步 LINQ 调用的结果集写入控制台:

var p = _context.Payment.Where(pp => pp.applicationNumber.Trim() == "12345");

p.ForEachAsync(payment => Console.WriteLine(payment.Amount));

因此测试没有写入在控制台对象被运行时清理之前的控制台(仅运行一个测试时)。

解决方案是首先将结果集转换为列表,这样我就可以使用 forEach() 的非异步版本:

var p = _context.Payment.Where(pp => pp.applicationNumber.Trim() == "12345").ToList();

p.ForEachAsync(payment =>Console.WriteLine(payment.Amount));

A different variant of the cause/solution:

My issue was that I was not getting an output because I was writing the result set from an asynchronous LINQ call to the console in a loop in an asynchronous context:

var p = _context.Payment.Where(pp => pp.applicationNumber.Trim() == "12345");

p.ForEachAsync(payment => Console.WriteLine(payment.Amount));

And so the test was not writing to the console before the console object was cleaned up by the runtime (when running only one test).

The solution was to convert the result set to a list first, so I could use the non-asynchronous version of forEach():

var p = _context.Payment.Where(pp => pp.applicationNumber.Trim() == "12345").ToList();

p.ForEachAsync(payment =>Console.WriteLine(payment.Amount));
反话 2024-10-20 09:34:58

Console.WriteLine 不起作用。在调试模式下,只有 Debug.WriteLine() 或 Trace.WriteLine() 可以工作。

我执行以下操作:在测试模块中包含使用 System.Diagnostics。然后,使用Debug.WriteLine作为我的输出,右键单击测试,然后选择调试选定的测试。结果输出现在将显示在下面的“输出”窗口中。我使用 Visual Studio 2017 版本 15.8.1,以及 Visual Studio 提供的默认单元测试框架。

Console.WriteLine won't work. Only Debug.WriteLine() or Trace.WriteLine() will work, in debug mode.

I do the following: include using System.Diagnostics in the test module. Then, use Debug.WriteLine for my output, right click on the test, and choose Debug Selected Tests. The result output will now appear in the Output window below. I use Visual Studio 2017 version 15.8.1, with the default unit test framework Visual Studio provides.

蓬勃野心 2024-10-20 09:34:58

如果您选择正确的输出(在输出窗口中找到的标有“显示输出”的下拉列表),Trace.WriteLine 应该可以工作。

Trace.WriteLine should work provided you select the correct output (the dropdown labeled with "Show output from" found in the Output window).

柏林苍穹下 2024-10-20 09:34:57

尝试使用 TestContext.WriteLine() 来输出测试结果中的文本。

示例:

[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:

要使用 TestContext,请在测试类中创建一个成员和属性 [...] 测试框架会自动设置该属性,然后您可以在单元测试中使用该属性。

Try using TestContext.WriteLine() which outputs text in test results.

Example:

[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...");
    }
}

The "magic" is described in MSDN:

To use TestContext, create a member and property within your test class [...] The test framework automatically sets the property, which you can then use in unit tests.

眼睛会笑 2024-10-20 09:34:57

我还试图让 Debug 或 Trace 或 Console 或 TestContext 在单元测试中工作。

这些方法似乎都不起作用或在输出窗口中显示输出:

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

Visual Studio 2012 及更高版本

(来自注释) 在 Visual Studio 2012 中,没有图标。相反,测试结果中有一个名为输出的链接。如果单击该链接,您将看到所有 WriteLine

在 Visual Studio 2012 之前,

我注意到在我的测试结果窗口中,运行测试后,在小成功绿色圆圈旁边,有另一个图标。我双击了它。这是我的测试结果,它包括上面所有类型的写入行。

I was also trying to get Debug or Trace or Console or TestContext to work in unit testing.

None of these methods would appear to work or show output in the output window:

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

Visual Studio 2012 and greater

(from comments) In Visual Studio 2012, there is no icon. Instead, there is a link in the test results called Output. If you click on the link, you see all of the WriteLine.

Prior to Visual Studio 2012

I then noticed in my Test Results window, after running the test, next to the little success green circle, there is another icon. I doubled clicked it. It was my test results, and it included all of the types of writelines above.

月隐月明月朦胧 2024-10-20 09:34:57

在 Visual Studio 2017 中,您可以看到测试资源管理器的输出。

1)在您的测试方法中,Console.WriteLine("something");

2) 运行测试。

3) 在“测试资源管理器”窗口中,单击“通过的测试方法”。

4)然后单击“输出”链接。

输入图像描述这里

点击“输出”,可以看到Console.Writeline()的结果。
输入图像描述这里

In Visual Studio 2017, you can see the output from test explorer.

1) In your test method, Console.WriteLine("something");

2) Run the test.

3) In Test Explorer window, click the Passed Test Method.

4) And click the "Output" link.

enter image description here

And click "Output", you can see the result of Console.Writeline().
enter image description here

惯饮孤独 2024-10-20 09:34:57

这取决于您的测试运行程序...例如,我正在使用 xUnit,以防万一这就是您正在使用的,请按照以下说明操作:

https://xunit.net/docs/capturing-output

此方法将您的输出与每个特定的单元测试进行分组。

using Xunit;
using Xunit.Abstractions;

public class MyTestClass
{
    private readonly ITestOutputHelper output;

    public MyTestClass(ITestOutputHelper output)
    {
        this.output = output;
    }

    [Fact]
    public void MyTest()
    {
        var temp = "my class!";
        output.WriteLine("This is output from {0}", temp);
    }
}

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

It depends on your test runner... for instance, I'm using xUnit, so in case that's what you are using, follow these instructions:

https://xunit.net/docs/capturing-output

This method groups your output with each specific unit test.

using Xunit;
using Xunit.Abstractions;

public class MyTestClass
{
    private readonly ITestOutputHelper output;

    public MyTestClass(ITestOutputHelper output)
    {
        this.output = output;
    }

    [Fact]
    public void MyTest()
    {
        var temp = "my class!";
        output.WriteLine("This is output from {0}", temp);
    }
}

There's another method listed in the link I provided for writing to your Output window, but I prefer the previous.

孤独岁月 2024-10-20 09:34:57

在 VS 2019

  1. 主菜单栏中的 VS 2019 中,单击:View -> 测试资源管理器
  2. 在测试资源管理器中右键单击您的测试方法 ->调试
  3. 单击附加输出链接,如下面的屏幕截图所示。

输入图像描述这里

你可以使用:

  • Debug.WriteLine
  • Console.WriteLine
  • TestContext.WriteLine

都将日志记录到附加输出窗口。

In VS 2019

  1. in the main VS menu bar click: View -> Test Explorer
  2. Right-click your test method in Test Explorer -> Debug
  3. Click the additional output link as seen in the screenshot below.

enter image description here

You can use:

  • Debug.WriteLine
  • Console.WriteLine
  • TestContext.WriteLine

all will log to the additional output window.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文