首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在运行时为NUnit测试提供参数

在运行时为NUnit测试提供参数,可以使用NUnit的TestCaseSource属性来实现。TestCaseSource属性允许你为测试方法提供多个参数集合,这些参数集合可以在运行时动态生成。

以下是一个简单的示例,演示如何使用TestCaseSource属性为NUnit测试提供参数:

代码语言:csharp
复制
using NUnit.Framework;

namespace MyTests
{
    public class TestClass
    {
        [Test]
        [TestCaseSource(typeof(TestData), nameof(TestData.TestCases))]
        public void MyTestMethod(int a, int b, int expectedResult)
        {
            // 在这里编写你的测试代码
        }
    }

    public static class TestData
    {
        public static IEnumerable<TestCaseData> TestCases
        {
            get
            {
                yield return new TestCaseData(2, 3, 5).SetName("Adding two positive integers");
                yield return new TestCaseData(-2, 3, 1).SetName("Adding a positive and a negative integer");
                yield return new TestCaseData(0, 0, 0).SetName("Adding two zeroes");
            }
        }
    }
}

在这个示例中,我们使用了TestCaseSource属性来指定TestData类中的TestCases属性作为测试方法MyTestMethod的参数来源。TestCases属性返回一个IEnumerable<TestCaseData>类型的集合,其中每个TestCaseData对象表示一组测试参数和预期结果。

在运行测试时,NUnit会使用TestCases属性返回的所有参数集合来执行MyTestMethod方法,并验证其结果是否符合预期。这样,你就可以在运行时为NUnit测试提供任意多的参数集合,从而实现更灵活和更具可重用性的测试。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券