Using NUnit - how can I get test equipment and name now?

I want to get the current NUnit executable test in a helper method that I use. In fact, we use NUnit for integration tests, not unit tests. When the test finishes, we would like the test to clear some log files when it was done. I currently hack this using the StackFrame class:

class TestHelper
{
    string CurrentTestFixture;
    string CurrentTest;
    public TestHelper()
    {
        var callingFrame = new StackFrame(1);
        var method = callingFrame.GetMethod();
        CurrentTest = method.Name;
        var type = method.DeclaringType;
        CurrentTestFixture = type.Name;
    }
    public void HelperMethod()
    {
        var relativePath = Path.Combine(CurrentTestFixture, CurrentTest);
        Directory.Delete(Path.Combine(Configurator.LogPath, relativePath));
    }
}

[TestFixture]
class Fix
{
    [Test]
    public void MyTest()
    {
        var helper = new TestHelper();
        //Do other testing stuff
        helper.HelperMethod();
    }
    [Test]
    public void MyTest2()
    {
        var helper = new TestHelper();
        //Do some more testing stuff
        helper.HelperMethod();
    }
}

This works just fine, unless I would like to make the TestHelper class part of my tool, for example:

[TestFixture]
class Fix
{
    private TestHelper helper;

    [Setup]
    public void Setup()
    {
        helper = new TestHelper();
    }

    [TearDown]
    public void TearDown()
    {
        helper.HelperMethod();
    }

    [Test]
    public void MyTest()
    {
        //Do other testing stuff
    }
    [Test]
    public void MyTest2()
    {
        //Do some more testing stuff
    }
}

, , . TestHelper... - .

- , .

​​?

+3
3

NUnit 2.5.7 "" TestContext. , , TestName. , , TearDown.

+3

, TestHelper, HelperMethod, ?

class TestHelper
{
    public void HelperMethod()
    {
        string CurrentTestFixture;
        string CurrentTest;

        var callingFrame = new StackFrame(1);
        var method = callingFrame.GetMethod();
        CurrentTest = method.Name;
        var type = method.DeclaringType;
        CurrentTestFixture = type.Name;

        var relativePath = Path.Combine(CurrentTestFixture, CurrentTest);
        Directory.Delete(Path.Combine(Configurator.LogPath, relativePath));
    }
}
0

-, , .

, , . , :

  • , . , , , , .
  • IDisposable

    [Test]
    public void MyTest()
    {
        using(new TestHelper())
        {
            ... test goes here ...
        }
    }
    
  • Or use PostSharp to weave the above code as part of the attribute of your test method.

    [Test, TestHelper]
    public void MyTest()
    {
       ...
    }
    

[EDIT]

fixed formatting. Added by IDisposable

0
source

Source: https://habr.com/ru/post/1752901/


All Articles