ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2019-11-09 02:08:24  阅读:13  来源: 互联网

标签:unit-testing nunit testing c



我想对我的方法进行测试,并且可以传递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

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有