How can I write output from a unit test?

后端 未结 15 958
误落风尘
误落风尘 2020-11-28 20:56

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 print

相关标签:
15条回答
  • 2020-11-28 21:35

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

    0 讨论(0)
  • 2020-11-28 21:36

    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.

    0 讨论(0)
  • 2020-11-28 21:39

    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.

    0 讨论(0)
  • 2020-11-28 21:39

    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.

    0 讨论(0)
  • 2020-11-28 21:39

    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.

    0 讨论(0)
  • 2020-11-28 21:40

    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.

    You can use:

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

    all will log to the additional output window.

    0 讨论(0)
提交回复
热议问题