【问题标题】:How to make a Unit test with several data sources?如何使用多个数据源进行单元测试?
【发布时间】:2016-07-17 09:07:33
【问题描述】:

我有一个方法,我想用两个数据源(在我的例子中是两个列表)来测试它。 有人可以帮助并解释如何使它正确吗? 我应该使用属性 TestCaseSource 以及如何使用?

 public void TestMethodIntToBin(int intToConvert, string result)
    {
        Binary converter = new Binary();
        string expectedResult = converter.ConvertTo(intToConvert);
        Assert.AreEqual(expectedResult, result);
    }

public List<int> ToConvert = new List<int>()
    {
        12,
        13,
        4,
        64,
        35,
        76,
        31,
        84
    };
    public List<string> ResultList = new List<string>()
    {
        "00110110",
        "00110110",
        "00121011",
        "00110110",
        "00110110",
        "00100110",
        "00110110",
        "00110110"
    };

【问题讨论】:

    标签: c# unit-testing testing nunit automated-tests


    【解决方案1】:

    首先,您的数据源需要是静态的。这是 NUnit 3 的要求。

    完成此操作后,您可以在每个参数上使用ValueSource attribute。例如,

    [Test, Sequential]
    public void TestMethodIntToBin([ValueSource(nameof(ToConvert))] int intToConvert, 
                                   [ValueSource(nameof(ResultList))] string result)
    {
        // Asserts
    }
    

    Sequential attribute 指定您希望 NUnit 通过按顺序选择值来生成测试用例。其他选项是Combinatorial,它会导致默认值的每个组合或Pairwise,它只是为所有可能的对创建案例。

    不过,在您的情况下,我建议将您的两个数据源合并为一个并使用TestCaseSource attribute

    [TestCaseSource(nameof(Conversions))]
    public void TestMethodIntToBin(int intToConvert, string result)
    {
        // Asserts
    }
    
    static object[] Conversions = {
        new object[] { 12, "00110110" },
        new object[] { 13, "00110110" }
    }
    

    请注意,我在 C# 6 中使用了 nameof() 运算符。如果您不使用 Visual Studio 2015,只需切换到字符串。

    【讨论】:

    • 另一种选择,对于这种情况可能更简单: [TestCaseSource(nameof(Conversions))] public void TestMethodIntToBin(int intToConvert, string result) { // Asserts } static object[] Conversions = { new object [] { 12, "00110110" }, 新对象[] { 13, "00110110" } }
    【解决方案2】:

    我似乎无法在此站点上将代码输入 cmets,因此我将其作为单独的答案发布,即使它实际上是对 Rob 答案的评论。

    在您的特定情况下,您根本不需要 TestCaseSource...考虑一下:

    [TestCase( 12, "00110110" )]
    [TestCase( 13, "00110110" )]
    public void TestMethodIntToBin(int intToConvert, string result)
    {
        // Asserts
    }
    

    【讨论】:

    • 正如查理所说,这可能是您发布的示例代码最简单的语法。这是首选方法,除非您的测试代码是动态生成的或来自外部系统。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多