c# - 如何在 NUnit 测试用例中传递字符串和字典?
问题描述
我想对我的方法进行测试,我可以传递 2 个字符串变量,但我不知道如何传递Dictionary<,>
.
它看起来像这样:
[Test]
[TestCase("agr1", "askdwskdls", Dictionary<TypeMeasurement,double>)]
public void SendDataToAgregator_GoodVariables_ReturnsOn(string agrID,string devID, Dictionary<TypeMeasurement, double> measurement)
{
}
TypeMeasurement
是enum
,我知道这不是你传递字典的方式,但我不知道如何,所以我把它放在那里,这样你就知道我想做什么。
解决方案
而不是TestCaseAttribute
,如果您有复杂的数据用作测试用例,您应该查看TestCaseSourceAttribute
TestCaseSourceAttribute 用于参数化测试方法,以标识将提供所需参数的属性、方法或字段
您可以使用以下构造函数之一:
TestCaseSourceAttribute(Type sourceType, string sourceName);
TestCaseSourceAttribute(string sourceName);
这是文档中的解释:
如果指定了 sourceType,则表示提供测试用例的类。它必须有一个默认构造函数。
如果未指定 sourceType,则使用包含测试方法的类。NUnit 将使用默认构造函数或 - 如果提供参数 - 这些参数的适当构造函数来构造它。
所以你可以像下面这样使用它:
[Test]
[TestCaseSource(nameof(MySourceMethod))]
public void SendDataToAgregator_GoodVariables_ReturnsOn(string agrID,string devID, Dictionary<TypeMeasurement, double> measurement)
{
}
static IEnumerable<object[]> MySourceMethod()
{
var measurement = new Dictionary<TypeMeasurement, double>();
// Do what you want with your dictionary
// The order of element in the object my be the same expected by your test method
return new[] { new object[] { "agr1", "askdwskdls", measurement }, };
};
推荐阅读
- netlogo - 使用列表在 netlogo 中绘制图形
- ios - 我正在尝试连接阿拉伯文和英文文本
- asp.net-mvc - 来自 MVC 的 Azure AD 登录:响应状态代码未指示成功:404(未找到)
- java - java.security.InvalidKeyException:错误的算法:需要 DESede 或 TripleDES
- sql - 为什么我的文本字段显示???在sql服务器中?
- javascript - javascript打开带有变量的新html
- angular - 如何将 Angular Resolver 用于没有路由配置的组件?
- python-3.x - Python3.5.2 反转方法字符串
- python-3.x - OpenCV(4.0.0) 断言在函数“contourArea”中失败
- python - 使用 pandas 从 Excel 中读取矩阵会根据所使用的 PC 提供 2 种不同的输出