如何在 NUnit 测试用例中传递字符串和字典? [英] How to pass string and dictionary in NUnit test cases?
问题描述
我想对我的方法进行测试,我可以传递 2 个字符串变量,但我不知道如何传递 Dictionary<,>
.
I want to make test for my method and I can pass 2 string variables, but I don't know how to pass the Dictionary<,>
.
看起来像这样:
[Test]
[TestCase("agr1", "askdwskdls", Dictionary<TypeMeasurement,double>)]
public void SendDataToAgregator_GoodVariables_ReturnsOn(string agrID,string devID, Dictionary<TypeMeasurement, double> measurement)
{
}
TypeMeasurement
是 enum
并且我知道这不是你传递字典的方式,但我不知道如何,所以我把它放在那里以便你知道什么我想做.
TypeMeasurement
is enum
and I know that this is not how you pass dictionary, but I don't know how, so I place it there so that you know what I want to do.
推荐答案
代替TestCaseAttribute
,如果你有复杂的数据作为测试用例,你应该看看TestCaseSourceAttribute
代码>
Instead of TestCaseAttribute
, if you have complex data to use as a test case, you should look at TestCaseSourceAttribute
TestCaseSourceAttribute 用于参数化测试方法,以标识将提供所需参数的属性、方法或字段
TestCaseSourceAttribute is used on a parameterized test method to identify the property, method or field that will provide the required arguments
您可以使用以下构造函数之一:
You can use one of the following contructors:
TestCaseSourceAttribute(Type sourceType, string sourceName);
TestCaseSourceAttribute(string sourceName);
这是文档的解释:
如果指定了 sourceType,则表示提供测试用例.它必须有一个默认构造函数.
If sourceType is specified, it represents the class that provides the test cases. It must have a default constructor.
如果未指定sourceType,则包含测试方法的类用来.NUnit 将使用默认构造函数来构造它或者 - 如果提供了参数 - 适当的构造函数参数.
If sourceType is not specified, the class containing the test method is used. NUnit will construct it using either the default constructor or - if arguments are provided - the appropriate constructor for those arguments.
所以你可以像下面这样使用它:
So you can use it like below:
[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 }, };
};
这篇关于如何在 NUnit 测试用例中传递字符串和字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!