code

단위 테스트에서 출력을 작성하는 방법은 무엇입니까?

codestyles 2020. 8. 29. 11:06
반응형

단위 테스트에서 출력을 작성하는 방법은 무엇입니까?


내 단위 테스트의 모든 호출은 디버깅 중에 건너 뛰 Debug.Write(line)거나 Console.Write(Line)출력이 인쇄되지 않습니다. 내가 사용하는 클래스 내에서 이러한 함수를 호출하면 잘 작동합니다.

단위 테스트가 자동화된다는 것을 이해하지만 여전히 단위 테스트에서 메시지를 출력하고 싶습니다.


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 에서 "테스트 프레임 워크가 자동으로 속성을 설정하므로 단위 테스트에서 사용할 수 있습니다."라고 설명되어 있습니다.


대화에 조금 늦었습니다.

또한 단위 테스트에서 작동하도록 Debug 또는 Trace 또는 Console 또는 TestContext를 가져 오려고했습니다.

이러한 방법 중 어느 것도 출력 창에 작동하거나 출력을 표시하지 않습니다.

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

VS2012 이상
(주석에서) Visual Studio 2012에는 아이콘이 없습니다. 대신 테스트 결과에 Output 이라는 링크가 있습니다. 링크를 클릭하면 모든 WriteLine.

VS2012 이전에는 테스트 결과 창에서 테스트를 실행 한 후 작은 성공 녹색 원 옆에 또 다른 아이콘이
있다는 것을 알았 습니다. 두 번 클릭했습니다. 그것은 내 테스트 결과였으며 위의 모든 유형의 글쓰기를 포함했습니다.


Visual Studio 2017에서는 테스트 탐색기의 출력을 볼 수 있습니다.

1) 테스트 메서드에서 Console.WriteLine ( "something");

2) 테스트를 실행합니다.

3) Test Explorer 창에서 Passed Test Method를 클릭합니다.

4) "출력"링크를 클릭합니다.

여기에 이미지 설명 입력

And click "Output", you can see the result of Console.Writeline(). 여기에 이미지 설명 입력


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.github.io/docs/capturing-output.html

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.


I think it is still actual.

You can use this NuGet package: https://www.nuget.org/packages/Bitoxygen.Testing.Pane/

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

To make trace more easy I can recommend to create 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));
    }
}

Solved with the following example:

public void CheckConsoleOutput()
    {
        Console.WriteLine("Hi Hi 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.


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 VS2008 has it) but you can still Use Debug.WriteLine when you run the test with Test With Debuggeroption in the IDE


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

Two options to try are:

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

  • Undefine DEBUG in your build settings for the unit test


I get no output when my Test/Test Settings/Default Processor Architecture setting and the assemblies that my test project references are not the same. Otherwise Trace.Writeline() works fine.


I'm using xunit so this is what I use: Debugger.Log(0, "1", input);

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


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


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, choose Debug Selected Tests. The result output will now appear in the Output window below. I use Visual Studio 2017 vs 15.8.1, with the default unit test framework VS provides.


Just ran into this. The cause/solution is a different variant of the above so I'll post.
My issue was that I was not getting an output because I was writing the result set from an async Linq call to console in a loop in an async context:

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

@jonzim이 언급했듯이 실제로 테스트 러너에 따라 다릅니다. NUnit 3 NUnit.Framework.TestContext.Progress.WriteLine()의 경우 Visual Studio 2017의 출력 창에서 출력을 실행하는 데 사용해야 했습니다.

NUnit과 방법에 대해 설명 : 여기

내 이해를 위해 이것은 테스트 실행자가받은 테스트 실행의 추가 병렬화를 중심으로 진행됩니다.

참고 URL : https://stackoverflow.com/questions/4786884/how-to-write-output-from-a-unit-test

반응형