简体   繁体   中英

How tear down integration tests

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.

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
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM