c# - xUnit中如何设置测试用例顺序

标签 c# xunit.net

我用 C# 编写了 xUnit 测试用例。那个测试类包含这么多方法。我需要按顺序运行整个测试用例。如何在 xUnit 中设置测试用例顺序?

最佳答案

在 xUnit 2.* 中,这可以使用 TestCaseOrderer 属性来指定排序策略来实现,该属性可用于引用在每个测试上注释的属性以表示顺序。

例如:

订购策略

[assembly: CollectionBehavior(DisableTestParallelization = true)] 

public class PriorityOrderer : ITestCaseOrderer
{
    public IEnumerable<TTestCase> OrderTestCases<TTestCase>(IEnumerable<TTestCase> testCases) where TTestCase : ITestCase
    {
        var sortedMethods = new SortedDictionary<int, List<TTestCase>>();

        foreach (TTestCase testCase in testCases)
        {
            int priority = 0;

            foreach (IAttributeInfo attr in testCase.TestMethod.Method.GetCustomAttributes((typeof(TestPriorityAttribute).AssemblyQualifiedName)))
                priority = attr.GetNamedArgument<int>("Priority");

            GetOrCreate(sortedMethods, priority).Add(testCase);
        }

        foreach (var list in sortedMethods.Keys.Select(priority => sortedMethods[priority]))
        {
            list.Sort((x, y) => StringComparer.OrdinalIgnoreCase.Compare(x.TestMethod.Method.Name, y.TestMethod.Method.Name));
            foreach (TTestCase testCase in list)
                yield return testCase;
        }
    }

    static TValue GetOrCreate<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey key) where TValue : new()
    {
        TValue result;

        if (dictionary.TryGetValue(key, out result)) return result;

        result = new TValue();
        dictionary[key] = result;

        return result;
    }
}

属性

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class TestPriorityAttribute : Attribute
{
    public TestPriorityAttribute(int priority)
    {
        Priority = priority;
    }

    public int Priority { get; private set; }
}

测试用例

[TestCaseOrderer("FullNameOfOrderStrategyHere", "OrderStrategyAssemblyName")]
public class PriorityOrderExamples
{
    [Fact, TestPriority(5)]
    public void Test3()
    {
        // called third
    }

    [Fact, TestPriority(0)]
    public void Test2()
    {
      // called second
    }

    [Fact, TestPriority(-5)]
    public void Test1()
    {
       // called first
    }

}

xUnit 2.* 订购 sample here

关于c# - xUnit中如何设置测试用例顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9210281/

相关文章:

c# - 在unity3D中,点击=触摸?

c# - Telerik RadWindow

c# - Xunit 2.3.0 无法将日期作为内联参数传递

c# - 使用匿名异步方法调用方法时,xUnit 测试挂起/死锁

xunit - 是否可以将 xUnit 与 LINQPad 一起使用?

.net-core - 如何从命令行运行 "dotnet xunit PathToLibrary.dll"(在持续集成中)

c# - 如何从 MIME 内容创建图像?

c# - 如何使用 C# 在 Redis 中添加对象列表作为键的值?

c# - Ajax.ActionLink 和确认对话框

c# - 使用异步方法在 Teamcity 上运行 xUnit 测试