其他分享
首页 > 其他分享> > CodeGo.net>如何在NUnit测试用例中传递字符串和字典?

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

作者:互联网

我想对我的方法进行测试,并且可以传递2个字符串变量,但是我不知道如何传递Dictionary<,>.

看起来像这样:

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

}

TypeMeasurement是枚举,我知道这不是您传递字典的方式,但是我不知道如何传递它,所以我将其放在那里,以便您知道我想做什么.

解决方法:

如果您有复杂的数据要用作测试用例,请使用TestCaseSourceAttribute代替TestCaseAttribute

TestCaseSourceAttribute is used on a parameterized test method to identify the property, method or field that will provide the required arguments

您可以使用以下构造函数之一:

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

这是从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.

因此,您可以像下面这样使用它:

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

标签:unit-testing,nunit,testing,c
来源: https://codeday.me/bug/20191109/2010894.html