【问题标题】:MSTest setup/teardown methods that run before and after ALL tests在所有测试之前和之后运行的 MSTest 设置/拆卸方法
【发布时间】:2022-06-15 00:42:32
【问题描述】:

相对于 Visual Studio 2019 中的 MSTest v2 而言是新的。TestInitialize 属性指示该方法应每个测试之前运行。同样,TestCleanup 表示该方法应每个测试之后运行。

[TestInitialize()]
public void Setup()
{
    // This method will be called before each MSTest test method
}

[TestCleanup()]
public void Teardown()
{
    // This method will be called after each MSTest test method has completed
}

如果你的测试类有N个方法,上面的方法会运行N次。

有没有一种方法可以指示只运行一次的类似设置和拆卸的方法?换句话说,对于所有 N 个测试的每次完整运行,每个方法将只运行一次。

NUnit3 和 xUnit v2.4.0 有类似的机制吗?

【问题讨论】:

    标签: unit-testing visual-studio-2019 nunit mstest xunit


    【解决方案1】:

    经过一番搜索,我偶然发现了this website with a MSTest "Cheat Sheet",其中包含我正在寻找的示例(在 MSTest 中):

    [ClassInitialize]
    public static void TestFixtureSetup(TestContext context)
    {
        // Called once before any MSTest test method has started (optional)
    }
    
    [ClassCleanup]
    public static void TestFixtureTearDown()
    {
        // Called once after all MSTest test methods have completed (optional)
    }
    

    ClassInitialize 方法必须是公共的、静态的、返回 void 并采用单个参数。 ClassCleanup 方法必须是公共的、静态的、返回 void 且不带参数。

    对于NUnit,属性引用可以是found here:

    [OneTimeSetUp]
    public void TestFixtureSetup()
    {
        // Called once before any NUnit test method has started (optional)
    }
    
    [OneTimeTearDown]
    public void TestFixtureTearDown()
    {
        // Called once after all NUnit test methods have completed (optional)
    }
    

    OneTimeSetUp 方法必须是公共的,但可以是静态方法或实例方法。 OneTimeTearDown 方法也一样。

    xUnit 似乎不支持 Setup / Teardown 功能。

    【讨论】:

      猜你喜欢
      • 2023-04-11
      • 1970-01-01
      • 2019-07-19
      • 2015-05-30
      • 1970-01-01
      • 2020-03-04
      • 2013-07-21
      • 2013-01-24
      • 2011-09-19
      相关资源
      最近更新 更多