单元测试LINQ Enumerables

时间:2014-04-04 06:28:21

标签: c# linq unit-testing

我目前正在接受单元测试和LINQ的教育,但我需要一些帮助。

对这些方法进行单元测试的正确方法是什么:

    /// <summary>
    /// Returns the product of all numbers.
    /// </summary>
    static public decimal Product<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal> selector)
    {
        return source.Aggregate<TSource, decimal>(1, (current, s) => current * selector(s));
    }

    /// <summary>
    /// Returns the product of all numbers.
    /// </summary>
    static public decimal? Product<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal?> selector)
    {
        return source.Select(selector).Aggregate<decimal?, decimal?>(1, (current, i) => current * i ?? 1);
    }

我真的无法弄清楚如何。无论我一直在努力;在运行代码覆盖率时,几个块始终保持未被覆盖。

我尝试过:

    [TestMethod]
    public void ExtendedProductAOfDecimalTest()
    {
        List<decimal?> items = new List<decimal?>(new decimal?[] { 5, 10, 15, 20, 25, 30 });
        Assert.AreEqual(11250000, Enumerable.Product(items, i => i));
    }

    [TestMethod]
    public void ExtendedProductBOfDecimalTest()
    {
        List<decimal> items = new List<decimal>(new decimal[] { 5, 10, 15, 20, 25, 30 });
        Assert.AreEqual(11250000, Enumerable.Product(items, i => i));
    }

1 个答案:

答案 0 :(得分:1)

我可以看到一个不会执行的部分。因为你的空合并运算符'?? 1'您还应该测试空值:

List<decimal?> items = new List<decimal?>(new decimal?[] { 5, 10, 15, 20, 25, 30 , null});