c# - 使用 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()' 不能与类型参数一起使用。显然,对象声明有问题,但我不知道如何修复它。
谢谢,
麦克风
解决方案
作为初学者,很容易使用简单的类型和数组,而且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);
}
}
与您的代码的差异:
- 使用 TestCaseData(不是必需的,但我认为更清楚)。
- 将值解析为整数。这就是问题的核心。
- 返回一个可枚举并使用
yield
(同样,不需要但可能更清楚)
注意:我只输入了这个,没有编译或运行。YMMV。
推荐阅读
- ms-access - 根据客户和购买日期添加编号
- django - 如何将嵌套字段的初始值更改为零而不是空值。?
- reactjs - react-admin SearchInput 搜索什么?
- javascript - Vue:当用户在子组件中增加商品时如何更新购物车总价
- c++ - EB GUIDE:在 QNX 上加载着色器插件时,缺少对 gtf::scdr::RenderObjectBase 的未定义引用
- azure-devops - 带有任务 Sonarqube https 的 Azure Pipepline
- bash - 如何理解这种 `find -prune` 的行为?
- sql - 检测昨天负载和今天负载之间差异但填充错误的查询
- django - 使用 Docker 创建 Django 项目时出现 Dockerfile 错误
- android - IllegalArgumentException: setTaskFromReuseOrCreateNewTask