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

能否在NUnit(C#)中像Pytest一样传入可迭代对象实现参数化测试?

Absolutely! NUnit has solid support for parameterized testing—you can totally replicate the behavior you’re used to with pytest’s @pytest.mark.parameterize decorator, and it even gives you a few flexible ways to do it. Let’s break down the approaches that fit your example best:

1. Using [TestCase] for explicit parameters

If you have a small set of values to test directly, you can list them out with the [TestCase] attribute. Each attribute triggers a separate run of your test method:

[TestCase(1)]
[TestCase(2)]
[TestCase(3)]
[TestCase(4)]
[TestCase(5)]
[TestCase("a")] // This will fail the assertion, just like your pytest example
[TestCase(6)]
[TestCase(7)]
[TestCase(8)]
public void TestData(object arg)
{
    // Match your pytest assertion: verify the argument is numeric
    Assert.That(int.TryParse(arg.ToString(), out _), Is.True);
}

2. Using [TestCaseSource] for an iterable data source

This is the closest match to your pytest setup, where you pass an iterable collection to drive test runs. First define your data set, then link it to the test method:

First, create your data source (can be a static field, static method, or separate class):

public static object[] TestDataValues = { 1, 2, 3, 4, 5, "a", 6, 7, 8 };

Then reference it with the [TestCaseSource] attribute:

[TestCaseSource(nameof(TestDataValues))]
public void TestDataFromSource(object arg)
{
    Assert.That(int.TryParse(arg.ToString(), out _), Is.True);
}

3. Using [ValueSource] for inline parameter linking

You can also attach the data source directly to the test method parameter with [ValueSource]:

public void TestDataWithValueSource([ValueSource(nameof(TestDataValues))] object arg)
{
    Assert.That(int.TryParse(arg.ToString(), out _), Is.True);
}

A quick note on your example

Just like in your pytest code, the "a" value will cause the assertion to fail. NUnit will run the test 9 times total—8 passing, 1 failing—exactly as you’d expect.

All these approaches automatically run your test method once per item in your data set, mirroring the behavior of pytest’s parameterized tests perfectly.

内容的提问来源于stack exchange,提问作者Ywapom

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:32:42