简体   繁体   English

使用 XUnit 将一个测试拆分为多个测试 - 避免 for 循环

[英]Splitting a test into multiple test with XUnit - Avoiding for loops

I have seen quite a bunch of threads showing how to pass data sets as input arguments to an XUnit test, but examples always have pretty limited amount of combinations to execute.我已经看到很多线程展示了如何将数据集作为输入参数传递给 XUnit 测试,但是示例中要执行的组合数量总是非常有限。
What if you were to run a test with N x M combinations?如果您要使用 N x M 组合运行测试怎么办?
An easy way to do it would be to write one test, taking no input argument and simply execute all combinations of the test using a loop in a loop.一种简单的方法是编写一个测试,不接受输入参数,并使用循环中的循环简单地执行测试的所有组合。
This approach is however not desired as it become impossible (without hacks) to dissociate the failing tests from the passing ones.然而,这种方法是不受欢迎的,因为将失败的测试与通过的测试分离是不可能的(没有黑客)。 It either all passes or all fails.它要么全部通过,要么全部失败。

Here is a bit of a sketch of the type of test using loops that I would like to avoid and therefore convert:这是使用我想避免并因此转换的循环的测试类型的一些草图:

[Fact]
public void NumberOfBytesPerBlockCannotExceedLimit()
{
    // Test setup
    ....

    // Repeat test for different number of bytes per word
    int[] bytesPerWordArray = new int[5] { 1, 3, 4, 6, 8, ... };
    foreach (int bytesPerWord in bytesPerWordArray)
    {
        // Repeat test N times, for different amount of reserved bytes
        int[] numReservedBytesArray= new int[5] { 1, 2, 3, 4, ... }; 
        foreach (int numReservedBytes in numReservedBytesArray)
        {
            // The actual test
            ...
        }
    }
}

Now, how do I split this test without having to type every combination/vector one by one in an inline or a IEnumerable/MemberData?现在,如何拆分此测试而不必在内联或 IEnumerable/MemberData 中逐一键入每个组合/向量?
Ideally, both bytesPerWordArray and numReservedBytesArray should be turned into some sorts of input vector!?理想情况下,bytesPerWordArray 和 numReservedBytesArray 都应该变成某种输入向量!?

Here's an example how to do it using MemberData :以下是如何使用MemberData执行此操作的MemberData

[Theory]
[MemberData(nameof(TestData))]
public void Test(int test1, int test2, int expected)
{
    var result = test1 + test2;
    Assert.Equal(expected, result);
}

public static IEnumerable<object[]> TestData()
{
    for (var i = 0; i < 5; i++)
    {
        for (var j = 0; j < 5; j++)
        {
            yield return new object[] { i, j, i + j };
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM