Search code examples
c#arraysnunitsequential

NUnit Sequential Attribute with arrays in Values


How I can pass string[][] arrays to ValuesAttribute?

I have:

public string[][] Array1 = new[] {new[] {"test1", "test2"}};
//...
[Test, Sequential]
public void SomeTest(
    [Values("val1", "val2", "val3")] string param1, 
    [Values(Array1, Array2, Array3)] string[][] param2) { //... }

And I've got Cannot access non-static field "Array1" in static context. Than I mark Array1 with static keyword and than I've got An attribute argument must be a constant expression... than I mark it with readonly keyword and still I have An attribute argument must be a constant expression...

Is here any way to pass multiple arrays? (Except ugly string[][][] and passing param2 indexes of relevant array[][] in array[][][])


Solution

  • It is possible. But you need to use TestCaseSourceAttribute instead of Sequential and Values.

    See an example:

    object[][] testCases = new[] {
    
        // test case 1
        new object[] {
            "val1",
            new[] { "test11", "test12" }
        },
    
        // test case 2
        new object[] {
            "val2",
            new[] { "test21", "test22" }
        },
    
        // test case 3
        new object[] {
            "val3",
            new[] { "test31", "test32", "test33", "test34" }
        }
    };
    
    [Test]
    [TestCaseSource("testCases")]
    public void SomeTest(string param1, string[] param2)
    {
        ...
    }
    

    Another benefits here: test cases are better organised and they can be easily reused in multiple tests.