如何拆除集成测试

我想对我的项目进行一些集成测试。 现在我正在寻找一种机制,允许我在所有测试开始之前执行一些代码,并在所有测试结束后执行一些代码。

请注意,我可以为每个测试设置方法和拆除方法,但我需要为所有测试提供相同的function。

请注意,我使用的是Visual Studio,C#和NUnit。

使用NUnit.Framework.TestFixture属性注释您的测试类,并使用NUnit.Framework.TestFixtureSetUp和NUnit.Framework.TestFixtureTearDown注释所有测试设置和所有测试拆解方法。

这些属性的function类似于SetUp和TearDown,但每个夹具只运行一次它们的方法,而不是每次测试之前和之后。

编辑以回应评论:为了在所有测试完成后运行方法,请考虑以下(不是最干净但我不确定更好的方法):

internal static class ListOfIntegrationTests { // finds all integration tests public static readonly IList 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 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 } } }