【问题标题】:Global test initialize method for MSTestMSTest 的全局测试初始化​​方法
【发布时间】:2010-11-28 11:39:27
【问题描述】:

快速提问,如何创建一个在解决方案中的所有测试运行之前只运行一次的方法。

【问题讨论】:

  • 我希望我也知道 :( 目前,我有一个抽象基类,每个 TestClass 都从该类继承。在该类中,我有一个 TestInitialize 方法。问题是,该方法每次都会被触发运行新测试!
  • 让抽象基类实现静态构造函数。在运行任何测试之前,它只会被触发一次。

标签: c# mstest


【解决方案1】:

创建一个公共静态方法,用AssemblyInitialize 属性修饰。测试框架将在每次测试运行时调用一次此 Setup 方法:

[AssemblyInitialize()]
public static void MyTestInitialize(TestContext testContext)
{}

对于TearDown

[AssemblyCleanup]
public static void TearDown() 
{}

编辑:

另外一个很重要的细节:这个方法所属的类必须用[TestClass]装饰。否则初始化方法不会运行。

【讨论】:

  • 如果您在多个程序集中进行了测试,那么 MyTestInitialize 将在您的测试运行中被多次调用。
  • 可能不清楚 - 这不是针对每个测试运行,而是针对每个测试运行。这意味着如果您运行一组测试,例如通过在一次测试运行中运行一个类中的所有测试或在一次测试运行中运行程序集中的所有测试,则该运行中的所有这些测试都会运行一次。因此,如果一次只运行一个测试,他们可以分享或不分享此方法的结果/副作用。
【解决方案2】:

为了强调@driis 和@Malice 在接受的答案中所说的内容,您的全局测试初始化​​程序类应该是这样的:

namespace ThanksDriis
{
    [TestClass]
    class GlobalTestInitializer
    {
        [AssemblyInitialize()]
        public static void MyTestInitialize(TestContext testContext)
        {
            // The test framework will call this method once -BEFORE- each test run.
        }

        [AssemblyCleanup]
        public static void TearDown() 
        {
            // The test framework will call this method once -AFTER- each test run.
        }
    }
}

【讨论】:

  • 在每个测试运行之前,标记为 [TestInitialize] 的类是否也将执行? AssemblyInitialize 是否也在每个测试运行之前运行,或者每个测试会话只运行一次? [TestInitialize()] 公共无效 TestInitialize() { ... } [TestCleanup()] 公共无效 TestCleanup() { ... }
  • 查看这个 StackOverflow 链接以获得关于使用 [TestInitialize] 装饰的代码何时运行的简洁答案:stackoverflow.com/a/23012750/165494
【解决方案3】:

对不起,糟糕的格式...

        /// <summary>
        /// Use TestInitialize to run code before running each test
        /// Runs before every test executes
        /// </summary>
        [TestInitialize()]
        public void TestInitialize()
        {
           ...
           ...
        }


        /// <summary>
        /// Use TestCleanup to run code after each test has run
        /// Runs after every test executes
        /// </summary>
        [TestCleanup()]
        public void TestCleanup()
        {
           ...
           ...
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-20
    • 2021-10-08
    • 2019-09-10
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多