c# - 如何将 new List<int> {1} 放入 NUNIT 测试用例中?

标签 c# tdd nunit testcase

我有方法:

public static int Add(List<int> numbers)
    {
        if (numbers == null || numbers.Count == 0)
            return 0;

        if (numbers.Count == 1)
            return numbers[0];


        throw new NotImplementedException();
    }

这是我针对它的测试,但它不喜欢 new List<int> {1}在测试用例中:

    [TestCase(new List<int>{1}, 1)]
    public void Add_WithOneNumber_ReturnsNumber(List<int> numbers)
    {

        var result = CalculatorLibrary.CalculatorFunctions.Add(numbers);

        Assert.AreEqual(1, result);
    }

它给我错误:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

我必须这样做吗:

    [Test]
    public void Add_WithOneNumber_ReturnsNumber()
    {

        var result = CalculatorLibrary.CalculatorFunctions.Add(new List<int>{7});


        Assert.AreEqual(7, result);

        var result2 = CalculatorLibrary.CalculatorFunctions.Add(new List<int> {3});

        Assert.AreEqual(4,result2);
    }

最佳答案

有一个选项可以使用 TestCaseSource 属性。在这里,我提供了一个非断言测试,有两种情况,只是为了看看它是如何工作的:

[TestFixture]
public class TestClass
{
    private static readonly object[] _sourceLists = 
    {
        new object[] {new List<int> {1}},   //case 1
        new object[] {new List<int> {1, 2}} //case 2
    };

    [TestCaseSource("_sourceLists")]
    public void Test(List<int> list)
    {
        foreach (var item in list)
            Console.WriteLine(item);
    }
}

无论如何,我不得不提到这不是最明显的解决方案,我更喜欢组织整齐的固定装置,而忽略了它们更冗长的事实

更多信息: https://github.com/nunit/docs/wiki/TestCaseSource-Attribute

关于c# - 如何将 new List<int> {1} 放入 NUNIT 测试用例中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19479817/

相关文章:

c# - 修复调用K8S API时出现 "The credentials supplied to the package were not recognized"问题

c# - WCF - 客户端端点配置错误

PHPUnit 测试实例

.net - TypeMock如何模拟密封类和非虚方法?

c# - 更新数据库中网页的查看次数

c# - 使用带偏移的 Raycast 命中点移动对象

unit-testing - 桌面应用程序和 Web 应用程序之间的区别

c# - 使用 nunit、xunit 或 visual studio 测试拆分测试定义和测试实现

c# - 使用 StreamWriter 作为参数之一对 void 方法进行单元测试

c# - FluentAssertions 类型检查