首页 > 解决方案 > 使用 C# 代码和文件中的测试用例进行 NUnit 测试的问题

问题描述

我是 C# 和 NUnit 初学者,尝试做一些简单的测试。

当我使用硬编码的测试用例例如 [TestCase(1, 2)] 时,一切正常。我想使用文本文件作为测试用例源,但不知道该怎么做。我在 StackOverflow 和其他地方找到了一些示例,但它不起作用。

// Code that works
namespace UnitTesting.GettingStarted.Tests
{

    [TestFixture]

    // this part works fine
    public class CalculatorTestMultiplication
    {
        [TestCase(1, 2)]
        [TestCase(2, 3)]
        [TestCase(3, 8)]
        [TestCase(1000, 1)]

        public void MultiplierParZero(int lhs, int rhs)
        {
            var systemUnderTest = new Calculator();
            Assert.NotZero(systemUnderTest.Multiply(lhs, rhs));

        }
    }
}

//Code with error

using System;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;

namespace UnitTesting.GettingStarted.Tests2
{
    public class CalculatorTestMultiplicationFile
    {
        static object[] TestData()
        {
            var reader = new StreamReader(File.OpenRead(@"C:\Test\MultiplicationZero.txt"));
            List<object[]> rows = new List<object[]>();

            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                var values = line.Split(',');
                rows.Add(values);
            }

            return rows.ToArray<object[]>();   // PROBLEM CODE
        }


        [TestCaseSource("TestCases")]
        public void MultiplyByZero(int lhs, int rhs)
        {

            var systemUnderTest = new Calculator();
            Assert.NotZero(systemUnderTest.Multiply(lhs, rhs));

        }
    }
}

与硬编码测试用例一样,如果参数不为零,我希望测试通过,这就是我在测试文件中的内容。我什至无法开始这个测试,因为在代码行中:“return rows.ToArray();”,我看到以下错误:非泛型方法 'List.ToArray()' 不能与类型参数一起使用。显然,对象声明有问题,但我不知道如何修复它。

谢谢,

麦克风

标签: c#unit-testingnunit

解决方案


作为初学者,很容易使用简单的类型和数组,而且object[]肯定非常简单。但是,使用 object 会使事情有些混乱,因为错误与参数的类型有关。如果您返回一组TestCaseData项目,每个项目代表一个测试用例,并且一次处理一个参数,这将更容易。

例如...

static IEnumerable<TestCaseData> TestData()
{
    var reader = new StreamReader(File.OpenRead(
        @"C:\Test\MultiplicationZero.txt"));

    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        var values = line.Split(',');
        // Assume there are exactly two items, and they are ints
        // If there are less than two or format is incorrect, then
        // you'll get an exception and have to fix the file. 
        // Otherwise add error handling.
        int lhs = Int32.Parse(values[0])
        int rhs = Int32.Parse(values[1]);
        yield return new TestCaseData(lhs, rhs);
    }
}

与您的代码的差异:

  1. 使用 TestCaseData(不是必需的,但我认为更清楚)。
  2. 将值解析为整数。这就是问题的核心。
  3. 返回一个可枚举并使用yield(同样,不需要但可能更清楚)

注意:我只输入了这个,没有编译或运行。YMMV。


推荐阅读