简体   繁体   English

单元测试LINQ可枚举

[英]Unit test LINQ Enumerables

I am currently getting myself educated on unittests and LINQ, but I need some help. 我目前正在接受有关单元测试和LINQ的教育,但是我需要一些帮助。

What would be a correct way of unittesting methods like these: 像这样的单元测试方法的正确方法是:

    /// <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);
    }

I really couldn't figure out how. 我真的不知道怎么做。 No matter what I keep trying; 不管我继续努力 when running Code Coverage, a few blocks always stay uncovered. 运行代码覆盖率时,始终会发现一些块。

What I have tried: 我尝试过的

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

I can see one part which would not execute. 我可以看到一部分无法执行。 Because of your null coalescing operator '?? 由于您合并了空运算符'?? 1' You should also test null values: 1'您还应该测试空值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM