How tear down integration tests

2019-06-14 11:05发布

I want to do some integration tests on my project. Now I am looking for a mechanism that allow me execute some code before all tests begin and execute some code after all tests ends.

Note that I can have set up methods and tear down method for each tests but I need the same functionality for all tests as a whole.

Note that I using Visual Studio, C# and NUnit.

1条回答
冷血范
2楼-- · 2019-06-14 11:41

Annotate your test class with the NUnit.Framework.TestFixture attribute, and annotate you all tests setup and all tests teardown methods with NUnit.Framework.TestFixtureSetUp and NUnit.Framework.TestFixtureTearDown.

These attributes function like SetUp and TearDown but only run their methods once per fixture rather than before and after every test.

EDIT in response to comments: In order to have a method run after ALL tests have finished, consider the following (not the cleanest but I'm not sure of a better way to do it):

internal static class ListOfIntegrationTests {
    // finds all integration tests
    public static readonly IList<Type> IntegrationTestTypes = typeof(MyBaseIntegrationTest).Assembly
        .GetTypes()
        .Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(MyBaseIntegrationTest)))
        .ToList()
        .AsReadOnly();

    // keeps all tests that haven't run yet
    public static readonly IList<Type> TestsThatHaventRunYet = IntegrationTestTypes.ToList();
}

// all relevant tests extend this class
[TestFixture]
public abstract class MyBaseIntegrationTest {
    [TestFixtureSetUp]
    public void TestFixtureSetUp() { }

    [TestFixtureTearDown]
    public void TestFixtureTearDown() {
        ListOfIntegrationTests.TestsThatHaventRunYet.Remove(this.GetType());
        if (ListOfIntegrationTests.TestsThatHaventRunYet.Count == 0) {
            // do your cleanup logic here
        }
    }
}
查看更多
登录 后发表回答