简体   繁体   English

如何在NUnit测试用例中传递字符串和字典?

[英]How to pass string and dictionary in NUnit test cases?

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<,> . 我想测试我的方法,我可以传递2个字符串变量,但我不知道如何传递Dictionary<,>

It looks like this: 它看起来像这样:

[Test]
[TestCase("agr1", "askdwskdls", Dictionary<TypeMeasurement,double>)]
public void SendDataToAgregator_GoodVariables_ReturnsOn(string agrID,string devID, Dictionary<TypeMeasurement, double> measurement)
{

}

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. TypeMeasurementenum ,我知道这不是你传递字典的方式,但我不知道怎么做,所以我把它放在那里让你知道我想做什么。

Instead of TestCaseAttribute , if you have complex data to use as a test case, you should look at TestCaseSourceAttribute 如果您有复杂的数据用作测试用例,而不是TestCaseAttribute ,您应该查看TestCaseSourceAttribute

TestCaseSourceAttribute is used on a parameterized test method to identify the property, method or field that will provide the required arguments TestCaseSourceAttribute用于参数化测试方法,以标识将提供所需参数的属性,方法或字段

You can use one of the following contructors: 您可以使用以下某个构造函数:

TestCaseSourceAttribute(Type sourceType, string sourceName);
TestCaseSourceAttribute(string sourceName);

This is explantion from the documentation : 这是文档中的解释

If sourceType is specified, it represents the class that provides the test cases. 如果指定了sourceType,则它表示提供测试用例的类。 It must have a default constructor. 它必须具有默认构造函数。

If sourceType is not specified, the class containing the test method is used. 如果未指定sourceType,则使用包含测试方法的类。 NUnit will construct it using either the default constructor or - if arguments are provided - the appropriate constructor for those arguments. NUnit将使用默认构造函数构造它,或者 - 如果提供了参数 - 将为这些参数构造适当的构造函数。

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 }, };
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM