阻止TestInitialize运行一个TestMethod方法

时间:2017-03-15 15:04:27

标签: c# unit-testing attributes

我有一组单元测试需要TestInitialize才能让它们运行...但是,有一个特定的测试,我希望能够在不运行TestInitialize的情况下运行。有没有办法做到这一点?

可能看起来像这样:

[TestClass]
public class BingBangBoom
{
    [TestInitialize]
    public void Setup()
    {
        // ...
    }

    [TestMethod]
    public void Bing()
    {
        // ...
    }

    [TestMethod]
    public void Bang()
    {
        // ...
    }

    [TestMethod(PreventInitialize)]
    public void Boom
    {
        // ...
    }
}

不用担心,如果没有,我可以提出替代解决方案

编辑 - RE DavidG:

这样做似乎很遗憾:

[TestClass]
public class BingBangBoom
{
    [TestInitialize]
    public void Setup()
    {
        // ...
    }

    // 10 very related methods
}

[TestClass]
public class BingBangBoom2
{
    // 1 method, even though it's entirely related to BingBangBoomin'
}

我猜它就是它。

1 个答案:

答案 0 :(得分:8)

这不是很明显,但肯定是可行的。

假设你有这样的属性:

public class SkipInitializeAttribute : Attribute { }

您需要的是测试类中的公共属性,以便通过测试框架注入:

public TestContext TestContext { get; set; }

然后像这样分支你的初始化:

[TestInitialize]
public void Initialize()
{
    bool skipInitialize = GetType().GetMethod(TestContext.TestName)
        .GetCustomAttributes<SkipInitializeAttribute>().Any();

    if (!skipInitialize)
    {
        // Initialization code here
    }
}

将样本作为自我测试的解决方案:

using System;
using System.Linq;
using System.Reflection;

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    public class SkipInitializeAttribute : Attribute
    {
    }

    [TestClass]
    public class UnitTest1
    {
        public TestContext TestContext { get; set; }

        private bool IsInitializationDone { get; set; }

        [TestInitialize]
        public void Initialize()
        {
            bool skipInitialize = GetType().GetMethod(TestContext.TestName).GetCustomAttributes<SkipInitializeAttribute>().Any();

            if (!skipInitialize)
            {
                // Initialization code here
                IsInitializationDone = true;
            }
        }

        [TestMethod]
        public void TestMethod1()
        {
            Assert.IsTrue(IsInitializationDone);
        }

        [TestMethod]
        [SkipInitialize]
        public void TestMethod2()
        {
            Assert.IsFalse(IsInitializationDone);
        }

        [TestMethod]
        public void TestMethod3()
        {
            Assert.IsTrue(IsInitializationDone);
        }
    }
}

结果:

Starting test execution, please wait...
Passed   TestMethod1
Passed   TestMethod2
Passed   TestMethod3

Total tests: 3. Passed: 3. Failed: 0. Skipped: 0.
Test Run Successful.

记住这个一般的想法,你可以玩基类/助手等。