全局测试初始化​​MSTest的方法

时间:2009-09-15 14:12:50

标签: c# mstest

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

3 个答案:

答案 0 :(得分:106)

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

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

TearDown

[AssemblyCleanup]
public static void TearDown() 
{}

修改

另一个非常重要的细节:此方法所属的类必须使用[TestClass]进行修饰。否则,初始化方法将不会运行。

答案 1 :(得分:1)

对不起,格式化...

        /// <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()
        {
           ...
           ...
        }

答案 2 :(得分:0)

只需强调一下@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.
        }
    }
}