Moerwald
Moerwald

Reputation: 11274

NUnit: Get testname in setup method

In NUnit I'm able to define a Setup method via the [Setup] attribute. The method has the signature public void Setup(). Is it possible to get the testname for that the Setup method is designated for?

Upvotes: 3

Views: 1421

Answers (1)

Rob Prouse
Rob Prouse

Reputation: 22647

In NUnit 3.x, just use TestContext.CurrentContext.Test.Name. There are also other properties on Test like MethodName or FullName depending on what you need.

[TestFixture]
public class TestNameInSetup
{
    [SetUp]
    public void SetUp()
    {
        var testName = TestContext.CurrentContext.Test.Name;
        TestContext.WriteLine($"SetUp for {testName}");
    }

    [Test]
    public void NamedTest()
    {
        var testName = TestContext.CurrentContext.Test.Name;
        TestContext.WriteLine($"Running test {testName}");
    }
}

Upvotes: 4

Related Questions