2014-04-04 108 views
0

我目前正在接受有關unittests和LINQ的教育,但我需要一些幫助。單元測試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

我可以看到這不會執行一個部分。由於你的空合併運算符'?? 1'您還應該測試空值:

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

運行此時,預期的答案更改爲0.是否預期的行爲?我會認爲它不是。編輯:當然,我應該買新的眼鏡。 – Matthijs

+0

在重寫了一些代碼後,它完美地工作。我使用了舊的選擇器而不是這裏顯示的選擇器。 – Matthijs