[英]How to skip a Unit Test at runtime?
提前致谢!
我们使用selenium Web驱动程序进行了一些自动化测试,这些测试很棒,并且提供了非常好的回归包。
现在的问题是我们的代码中有功能切换。 因此,我必须说忽略这些测试,除非该功能切换已打开/关闭。 我找不到真正能搜索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的逻辑已关闭的方法,然后不要运行此测试-看过动态添加[忽略]但没有运气。
这是通过VSTS运行的,我可以使用[TestCategories],但是我必须不断更新打开/关闭功能的管道,而这是我不想做的。
任何帮助或建议将是巨大的!
根据我的阅读此 ,您可能需要使用Assert.Inconclusive
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()
{
//...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.