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

使用NUnit时能否在SetUp方法中构建TestCaseSource列表?

结论

不可以在[SetUp]方法中构造[TestCaseSource]依赖的TestCaseData列表,这是你当前测试被跳过的核心原因。

根因说明

NUnit的测试用例发现流程早于所有测试执行生命周期方法:[TestCaseSource] 标注的数据源会在测试加载阶段(早于[SetUp]、[OneTimeSetUp]的执行时间)就完成读取,此时你定义的rootElementsTypesData还是空列表,NUnit识别不到可用的测试用例,就会直接跳过该测试方法。

此外你当前的写法还存在额外隐患:[SetUp]会在每个测试用例执行前都运行一次,静态列表会被重复添加数据,即便时机正确也会出现用例重复的问题。

可行解决方案

方案1:单测试方法内遍历断言

如果不需要每个测试场景单独展示用例结果,直接把测试用例构造逻辑搬到测试方法内部即可,符合常规测试执行顺序:

[TestFixture]
public class DirectReader
{
    private XDocument document;
    private DirectUblReader directReader;
    private UblReaderResult result;

    [SetUp]
    public void Setup()
    {
        var fileStream = ResourceReader.GetScenario("RequiredElements_2_1.xml");
        document = XDocument.Load(fileStream);
        directReader = new DirectUblReader();
        result = directReader.Read(document);
    }

    [Test]
    public void Expects_TypeOfObject_ToBeTheSameAs_InputValue()
    {
        var testCases = new List<(object inputValue, Type expectedType)>()
        {
            (result.Invoice.Id, typeof(IdentifierType)),
            (result.Invoice.IssueDate, typeof(IdentifierType))
        };
        foreach (var testCase in testCases)
        {
            Assert.That(testCase.inputValue, Is.TypeOf(testCase.expectedType));
        }
    }
}

方案2:数据源方法内完成资源初始化

如果需要每个场景作为独立测试用例展示结果,把资源加载逻辑直接搬到TestCaseSource指向的方法内即可:

[TestFixture]
public class DirectReader
{
    private static IEnumerable<TestCaseData> RootElementsTypesData()
    {
        using var fileStream = ResourceReader.GetScenario("RequiredElements_2_1.xml");
        var document = XDocument.Load(fileStream);
        var directReader = new DirectUblReader();
        var result = directReader.Read(document);
        
        yield return new TestCaseData(result.Invoice.Id, typeof(IdentifierType));
        yield return new TestCaseData(result.Invoice.IssueDate, typeof(IdentifierType));
    }

    [Test, TestCaseSource(nameof(RootElementsTypesData))]
    public void Expects_TypeOfObject_ToBeTheSameAs_InputValue(object inputValue, Type expectedType)
    {
        Assert.That(inputValue, Is.TypeOf(expectedType));
    }
}

该方案下资源加载只会在测试发现阶段执行一次,不会重复执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 21:39:03