NUnit Pass variable from [Test] to [TearDown]

Viewed 20

I need to pass the variable that contains Guid to the TearDown method. Something like this:

    [Test]
    public void MyTest()
    {
        ...
        var myVariable = $"Test-{Guid.NewGuid()}";
        ...
    }

So, I need to pass this 'myVariable' to the TearDown:

    [TearDown]
    public void TearDown()
    {
        ...
        DoSomethingWith(myVariable);
        ...
    }

I tried to set the Category for my Test, but it does not work with Guid Also I tried to figure out how to parse myVariable from TestContext.CurrentContext... obj, but wasn't success :(

1 Answers

Make it a field instead of a variable.

class MyTest
{
    string? myField = null;

    [Test]
    public void MyTest()
    {
        ...
        myField = $"Test-{Guid.NewGuid()}";
        ...
    }

    [TearDown]
    public void TearDown()
    {
        ...
        DoSomethingWith(myField);
        ...
    }
}
Related