为何params对字符串数组与整数数组表现不同?NUnit测试疑问
[TestCase(new[] { "1", "2", "3" })] Doesn't Work in NUnit? 这个问题的核心其实是C#的数组协变特性和params参数的重载解析规则共同作用的结果,结合NUnit的TestCaseAttribute构造函数设计就很容易理解:
Key Background
NUnit's core TestCaseAttribute constructor looks like this:
public TestCaseAttribute(params object[] arguments)
And a critical C# array rule: Reference-type arrays can implicitly convert to arrays of their parent types (e.g., string[] can directly cast to object[]), but value-type arrays cannot (e.g., int[] can't become object[]).
Breakdown of Your Examples
Works:
[TestCase(new[] { 1, 2, 3 })]int[]is a value-type array, so it can't implicitly convert toobject[]. The compiler treats the entire integer array as a singleobjectinstance, packing it into theparams object[] argumentsarray as its only element. NUnit receives this singleint[]parameter and passes it directly to your test method (which expects anint[]), so everything matches perfectly.Works:
[TestCase("Other string", new[] { "1", "2", "3" })]
Here you're passing two distinct parameters, so there's no ambiguity. The compiler adds both"Other string"and thestring[]as separate elements to theparams object[] argumentsarray. NUnit receives these two parameters, which aligns with a test method expectingstring + string[]parameters.Fails:
[TestCase(new[] { "1", "2", "3" })]string[]is a reference-type array, so it can implicitly convert toobject[]. The compiler treats yourstring[]as theparams object[] argumentsarray itself—meaningargumentsends up containing three separate string elements ("1","2","3"), not onestring[]element.
If your test method expects one string[] parameter, NUnit will throw a mismatch error: it sees 3 string parameters being passed, but your method only accepts 1 array parameter. That's why this test case fails.
Fix
To pass a standalone string[] as a test parameter, force the compiler to treat it as a single object by casting it explicitly:
[TestCase((object)new[] { "1", "2", "3" })]
This tells the compiler to wrap the string[] into the params object[] arguments array as a single element, so NUnit correctly recognizes it as one array parameter for your test method.
内容的提问来源于stack exchange,提问作者Maciej Stachowski

