You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何params对字符串数组与整数数组表现不同?NUnit测试疑问

Why [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

  1. Works: [TestCase(new[] { 1, 2, 3 })]
    int[] is a value-type array, so it can't implicitly convert to object[]. The compiler treats the entire integer array as a single object instance, packing it into the params object[] arguments array as its only element. NUnit receives this single int[] parameter and passes it directly to your test method (which expects an int[]), so everything matches perfectly.

  2. 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 the string[] as separate elements to the params object[] arguments array. NUnit receives these two parameters, which aligns with a test method expecting string + string[] parameters.

  3. Fails: [TestCase(new[] { "1", "2", "3" })]
    string[] is a reference-type array, so it can implicitly convert to object[]. The compiler treats your string[] as the params object[] arguments array itself—meaning arguments ends up containing three separate string elements ("1", "2", "3"), not one string[] 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:29:53