如何在运行时跳过单元测试?

8

提前感谢!

我们有一些使用selenium web driver的自动化测试,它们非常好,并提供了一个非常好的回归包。

问题是现在我们的代码中有功能切换。因此,除非该功能切换已打开/关闭,否则我需要忽略这些测试。我在Google上搜索了很多,但没有找到什么有用的信息。

理想情况下,我不希望在特性测试的顶部放置“if”语句,但看起来这将是主要方法。我的初步想法是创建一个自定义属性。

public class IsFeatureFlagTurnedOn : Attribute
{
   public IsFeatureFlagTurnedOn(string featureToggleName)
   {
      FeatureToggleName = featureToggleName;
   }
   public string FeatureToggleName {get;}
}

public class MyTests 
{
   [TestMethod]
   [IsFeatureFlagTurnedOn("MyFeature1")]
   public void ItShould()
   {
      // only run if MyFeature1 is turned on
   }
}

我需要以某种方式钩入MSTest管道,并且如果存在这个属性并且MyFeature1的逻辑被关闭,则不运行此测试。尝试动态添加[Ignore],但没有成功。
此操作通过VSTS运行,我可以使用[TestCategories],但我不想不断更新已开启/关闭的功能管道。
任何帮助或建议将是很好的!
2个回答

8

MSTest v2现在有很多可扩展性点,您可以通过扩展TestMethodAttribute来实现此目的。首先,我们添加两个属性参数,一个用于属性名称的string和包含属性的Type。然后我们重写Execute方法并通过反射调用属性。如果结果为true,我们将正常执行测试,否则返回“不确定”的测试结果。

public class TestMethodWithConditionAttribute : TestMethodAttribute
{
    public Type ConditionParentType { get; set; }
    public string ConditionPropertyName { get; set; }

    public TestMethodWithConditionAttribute(string conditionPropertyName, Type conditionParentType)
    {
        ConditionPropertyName = conditionPropertyName;
        ConditionParentType = conditionParentType;
    }

    public override TestResult[] Execute(ITestMethod testMethod)
    {
        if (ConditionParentType.GetProperty(ConditionPropertyName, BindingFlags.Static | BindingFlags.Public)?.GetValue(null) is bool condiiton && condiiton)
        {
            return base.Execute(testMethod);
        }
        else
        {
            return new TestResult[] { new TestResult {  Outcome = UnitTestOutcome.Inconclusive } };
        }
    }
}

现在我们可以像这样使用新属性:
[TestClass]
public class MyTests
{
    [TestMethodWithCondition(nameof(Configuration.IsMyFeature1Enabled), typeof(Configuration))]
    public void MyTest()
    {
        //...
    }
}

public static class Configuration
{
    public static bool IsMyFeature1Enabled => false;
}

上述是一个非常通用的解决方案。您还可以根据特定的用例进行更多自定义,以避免在属性声明中使用过多冗长的语言:

public class TestMethodForConfigAttribute : TestMethodAttribute
{
    public string Name { get; set; }

    public TestMethodForConfigAttribute(string name)
    {
        Name = name;
    }

    public override TestResult[] Execute(ITestMethod testMethod)
    {
        if (IsConfigEnabled(Name))
        {
            return base.Execute(testMethod);
        }
        else
        {
            return new TestResult[] { new TestResult {  Outcome = UnitTestOutcome.Inconclusive } };
        }
    }

    public static bool IsConfigEnabled(string name)
    {
        //...
        return false;
    }
}

然后像这样使用:

[TestClass]
public class MyTests
{
    [TestMethodForConfig("MyFeature1")]
    public void MyTest()
    {
        //...
    }
}

太棒了!#H5YR - user1829226

1

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