IEnumerable <t>的具体实现,不是ICollection <t>

时间:2016-06-15 11:22:21

标签: c# collections nunit ienumerable test-coverage

我想知道.net框架中实现IEnumerable的任何类是否都没有实现ICollection接口。

我问它是因为我在以下扩展方法中无法获得100%的代码覆盖率:

public static int GetSafeCount<T>(this IEnumerable<T> nullableCollaction)
    {
        if (nullableCollaction == null)
        {
            return 0;
        }
        var collection = nullableCollaction as ICollection<T>;
        if (collection != null)
        {
            return collection.Count;
        }
        return nullableCollaction.Count();
    }

我的任何测试都没有涵盖最后一行,我无法找到正确的类进行实例化以覆盖它。

我的测试代码是:

[Test]
    public void GetSafeCount_NullObject_Return0()
    {
        IEnumerable<string> enumerable=null;

        Assert.AreEqual(0, enumerable.GetSafeCount());
    }
    [Test]
    public void GetSafeCount_NonICollectionObject_ReturnCount()
    {
        IEnumerable<string> enumerable = new string[]{};

        Assert.AreEqual(0, enumerable.GetSafeCount());
    }

3 个答案:

答案 0 :(得分:2)

只需使用任何LINQ操作,例如Where

[Test]
public void GetSafeCount_NonICollectionObject_ReturnCount()
{
    IEnumerable<string> enumerable = new string[0].Where(x => x.Length == 0);
    Assert.AreEqual(0, enumerable.GetSafeCount());
}

但是,您可以通过推迟Enumerable.Count()来简化您的实施,我期望以您希望的方式对其进行优化:

public static int GetSafeCount<T>(this IEnumerable<T> nullableCollection)
    => nullableCollection == null ? 0 : nullableCollection.Count();

或者:

public static int GetSafeCount<T>(this IEnumerable<T> nullableCollection)
    => nullableCollection?.Count() ?? 0;

(两者都假设C#6 ......)

此时,只有两个测试是有意义的:一个用于空参数,一个用于非空参数。

答案 1 :(得分:1)

您可以使用Stack<T>类,它实现ICollectionIEnumerable<T>但不实现ICollection<T>

以下是该类的定义方式:

public class Stack<T> : IEnumerable<T>, IEnumerable, ICollection, 
    IReadOnlyCollection<T>

答案 2 :(得分:0)

他是IEnumerable<T>的一个例子,不是ICollection<T>

public class MyClass : IEnumerable<int>
{
    public List<int> ints = new List<int> { 1, 2, 3, 4, 5 };

    public IEnumerator<int> GetEnumerator()
    {
        foreach (var i in ints)
        {
            yield return i;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this as IEnumerator;
    }
}

现在你可以这样做:

foreach(var item in new MyClass())
{
    // do something
}

但不能这样做,因为它不是ICollection

var coll = new MyClass() as ICollection<int>; // null!!!