MSTest的全局测试初始化方法

76

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


我也希望我知道 :( 目前,我有一个抽象基类,每个TestClass都从中继承。在该类内部,我有一个TestInitialize方法。问题是,每次运行新测试时,该方法都会被触发! - Pure.Krome
1
让那个抽象基类实现一个静态构造函数。它将在任何测试运行之前仅被触发一次。 - mglmnc
3个回答

137

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

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

对于TearDown,它的:

[AssemblyCleanup]
public static void TearDown() 
{}

编辑:

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


4
如果您的测试涉及多个程序集,则MyTestInitialize将为测试运行调用多次。 - BenCr
2
可能不太清楚 - 这个方法并非针对每个测试运行,而是针对每个测试运行的集合。也就是说,如果您通过在一个测试运行中运行类中的所有测试或程序集中的所有测试来运行一组测试,则此方法将在该运行中为所有这些测试运行一次。因此,它们可以共享此方法的结果/副作用,或者如果一次只运行一个测试,则不能共享。 - bcr

8

强调一下已被接受答案中@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()] public void TestInitialize() { ... } [TestCleanup()] public void TestCleanup() { ... } - Allen
1
请查看此StackOverflow链接,了解有关使用[TestInitialize]修饰的代码何时运行的简明答案:https://dev59.com/EWAg5IYBdhLWcg3w7uyk#23012750 - Mass Dot Net

0

对于糟糕的格式化我表示抱歉...


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

这将停止您的测试运行(或被发现),代码应为:public static void TestInitialize(TestContext testContext) - Milan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接