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

标签 c# unit-testing testing nunit

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

看起来像这样:

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

}

TypeMeasurementenum我知道这不是你传递字典的方式,但我不知道如何,所以我把它放在那里让你知道我想做什么。

最佳答案

而不是 TestCaseAttribute,如果您有复杂的数据用作测试用例,您应该查看 TestCaseSourceAttribute

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

关于c# - 如何在 NUnit 测试用例中传递字符串和字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50437491/

相关文章:

c++ - 在同一个函数/程序中使用 WebSocket++ 服务器和客户端

node.js - 我可以使用 karma 来测试拖放之类的页面交互吗?

ruby-on-rails-3 - 轨道测试 : session mechanism creates new cart instead of using fixture

c# - 仅授权 ASP.NET Core 中的某些 Http 方法

c# - 将参数传递给 dotnet 测试项目?

c# - 将聚合函数作为参数传递

python - python (2.7) unittest 的测试描述如何修改

entity-framework - 内存数据库中的 Entity Framework (代码优先)用于单元测试

linux - 带 Shell 的 Qt 程序

c# - 如何返回第一个不为 null 或空的字符串变量