【问题标题】:How to pass string and dictionary in NUnit test cases?如何在 NUnit 测试用例中传递字符串和字典?
【发布时间】:2018-05-20 17:18:03
【问题描述】:

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

看起来像这样:

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

}

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

【问题讨论】:

    标签: c# unit-testing testing nunit


    【解决方案1】:

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

    TestCaseSourceAttribute 用于参数化测试方法,以识别将提供所需参数的属性、方法或字段

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

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

    这是documentation的解释:

    如果指定了 sourceType,它表示提供 测试用例。它必须有一个默认构造函数。

    如果未指定sourceType,则包含测试方法的类 用来。 NUnit 将使用默认构造函数来构造它 或 - 如果提供了参数 - 那些的适当构造函数 论据。

    所以你可以像下面这样使用它:

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

    【讨论】:

    • 我试过这个,但现在编译器说我没有足够的参数,他从中创建了 3 个测试用例。 @CodeNotFound
    • @Serlok 应该是return new[] { new object[] { "agr1", "askdwskdls", measurement }, };。如果您愿意,也可以将属性的类型更改为 static object[][] MySourceProperty 以清楚起见。或IEnumerable&lt;object[]&gt;(在这种情况下,您可以使用yield return,如果您愿意)。
    • 我编辑了我的答案@Serlok 你应该返回一个数组数组:)
    • 为防止出现拼写错误和误认为该属性未被使用,您可以将[TestCaseSource("MySourceProperty")] 更改为[TestCaseSource(nameof(MySourceProperty))]
    • @JeppeStigNielsen 先生,您在尝试了 2 小时后才帮助了我,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 2021-12-19
    • 2014-06-04
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多