How to pass string and dictionary in NUnit test cases?

时光毁灭记忆、已成空白 提交于 2019-12-22 10:19:02

问题


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<,>.

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.


回答1:


Instead of TestCaseAttribute, if you have complex data to use as a test case, you should look at 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);

This is explantion from the documentation:

If sourceType is specified, it represents the class that provides the test cases. It must have a default constructor.

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


来源:https://stackoverflow.com/questions/50437491/how-to-pass-string-and-dictionary-in-nunit-test-cases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!