Alex Wang
Alex Wang

Reputation: 481

Cannot Console.WriteLine in NUnit OneTimeSetUp and OneTimeTearDown under SetUpFixure

I just created a very simple NUnit test project in Visual Studio (.NET Core 3.1)

using NUnit.Framework;
using System;

namespace TestProject1
{
    [SetUpFixture]
    public class MySetUpClass
    {
        [OneTimeSetUp]
        public void RunBeforeAnyTests()
        {
            Console.WriteLine("Initialize");
        }

        [OneTimeTearDown]
        public void RunAfterAnyTests()
        {
            Console.WriteLine("Teardown");
        }
    }

    [TestFixture]
    public class Tests
    {
        [Test]
        public void Test1()
        {
            Console.WriteLine("Running test");
            Assert.Pass();
        }
    }
}

However, after I run the test and open the additional output for the result in Visual Studio, it only contains "Running test", without "Initialize" and "Teardown". How could this happen?

Upvotes: 2

Views: 1420

Answers (2)

srk
srk

Reputation: 1901

How are you running the test? It works for me with ReSharper. Maybe try a different test runner.

One thing I would point out: in ReSharper, I have to select the SetUpFixture in order to see the console log from that class.

When I select the test:

Console log for test

When I select the SetUpFixture:

Console log for test fixture

Do you actually need to write to the console from your OneTimeSetUp/OneTimeTearDown? Or are you simply using the console to verify that those methods get called? If the latter, perhaps just set a breakpoint in those methods rather than writing to the console.

Upvotes: 2

Charlie
Charlie

Reputation: 13736

It's up to the runner to display output. In many cases, an actual console is not available, therefore NUnit traps any console output and provides it to the runner as an event.

The NUnit console runner simply displays that info to the console. Most GUI runners display it in a window somewhere. The Visual Studio Test Explorer, unfortunately, only displays output associated with a test case (method).

Upvotes: 1

Related Questions