c# - 基类中的 NUnit TestCaseSource 具有来自派生类的数据

标签 c# nunit testcase base-class

我想知道是否有一种方法可以在基测试类中使用 TestCaseSource 以及以通用方式从派生类给出的数据。

例如,如果我有以下基类:

public abstract class Base<T>
{
    protected static T[] Values;

    [TestCaseSource(nameof(Values))]
    public void MyTest(T[] values)
    {
        // Some test here with the values;
    }

}

以及以下派生类

[TestFixture]
public class Derived : Base<string>
{

    [OneTimeSetup]
    public void OneTimeSetup()
    {
        Values = new[] { "One", "Two" };
    }

    [TestCaseSource(nameof(Values))
    public void DerivedSpecificTest(T[] values)
    {
        // Some test here with the values;
    }

}

我认为我所做的事情是不正确的,因为当我运行派生类测试时,我在两个测试中都遇到了此异常:失败:System.Exception:找不到测试用例源。

但是,该示例应该能够说明我正在尝试做的事情(如果我正在尝试做的事情是可能的)。本质上,我想知道是否可以在基类中使用 TestCaseSource 以及派生类给出的数据。

感谢任何帮助,如果需要澄清,我可以回答问题。

我还应该提到,如果我将 Values 初始化为空的零长度数组,测试将返回不确定的结果。我认为这是因为在创建测试时数据发生了变化(NUnit 的某些行为?)。

如果我不使用 TestCaseSource,而是只需使用属性 Test 标记测试,并将我的测试逻辑插入到每个数组值的循环。这并不理想,因为当测试失败时,很难准确地看出哪个输入导致其失败,因为每个输入都没有被分离出来。

最佳答案

这应该可以帮助您入门,毫无疑问有一个更优雅的解决方案。

using System;
using NUnit.Framework;

namespace UnitTestProject1
{
    public class Base<T>
    {
        private static T[] Values;

        [TestCaseSource(nameof(Values))]
        public void MyTest(T value)
        {
            Console.WriteLine($"Base: {value}");
            // Some test here with the values;
        }
    }

    [TestFixture]
    public class Derived : Base<string>
    {
        private static string[] Values= new[] { "One", "Two" };

        [TestCaseSource(nameof(Values))]
        public void DerivedSpecificTest(string value)
        {
            // Some test here with the values;
            Console.WriteLine($"Derived: {value}");
        }
    }
}

关于c# - 基类中的 NUnit TestCaseSource 具有来自派生类的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59416839/

相关文章:

C#。文档转换为 PDF

c# - mvc重复用户验证错误

c# - 如何反序列化 JSon 复杂类型 C#

exception - NUnit 测试 : Is IDisposable guaranteed if a non-expected exception is thrown?

.net - 使用 ReSharper 在 .NET Core 中运行 NUnit 测试

javascript - 如何编写 JavaScript 测试用例

c# - 为什么我在这个数据绑定(bind)上得到 "type reference cannot find a public type"?

c# - [Test]和[Test()]的Nunit方法和类属性声明区别

Selenium、FluentAutomation 和 NUnit - 如何为每个测试用例切换浏览器?

php - 如何检查PHPUnit正确抛出的异常?