[英]How can IEnumerable.GetEnumerator()'s go-to implemetation is to return GetEnumerator(), if GetEnumerator() is of diffrent return type?
[英]C#: How do you test the IEnumerable.GetEnumerator() method?
假設我舉例說這個類生成Fibonacci數:
public class FibonacciSequence : IEnumerable<ulong>
{
public IEnumerator<ulong> GetEnumerator()
{
var a = 0UL;
var b = 1UL;
var c = a + b;
while (true)
{
yield return c;
c = a + b;
a = b;
b = c;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
然后我可以編寫一個測試,確保序列中的n個第一個數字是正確的。
[Test]
public void GetEnumerator_FirstFifteenNumbers_AreCorrect()
{
var sequence = new FibonacciSequence().Take(15).ToArray();
CollectionAssert.AreEqual(sequence, new[] {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610});
}
但是,當我檢查覆蓋范圍時,我會看到IEnumerable.GetEnumerator()方法未經測試,我的覆蓋率將低於它真正需要的范圍。 很公平。 但是我該如何測試這種方法呢?
你通常如何處理這個問題?
編輯:根據Marc所說的更新。
那么你可以通過以下方式獲得覆蓋:
// Helper extension method
public static IEnumerable AsWeakEnumerable(this IEnumerable source)
{
foreach (object o in source)
{
yield return o;
}
}
...
[Test]
public void GetEnumerator_FirstFifteenNumbers_AreCorrect()
{
IEnumerable weak = new FibonacciSequence().AsWeakEnumerable();
var sequence = weak.Cast<int>().Take(15).ToArray();
CollectionAssert.AreEqual(sequence,
new[] {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610});
}
請注意, weak
被聲明為非泛型IEnumerable
類型...這意味着您需要在其上調用Cast
以將每個返回的對象Cast
轉換為int
。
我不確定我會打擾......
我不會測試它。 我會嘗試從coverage工具中過濾掉該方法。 我認為報道應該檢查我想要涵蓋的內容而不是所有內容。 從其他評論您似乎使用TestDriven.Net。 我不知道過濾器有多好,但NCover可能。 您也可以嘗試PartCover。
你必須使用IEnumerable
(非泛型); 我使用Cast<T>
發布了一個回復,但是仍然會作弊(它檢查了所需的類型作為特殊情況) - 您可能需要以下內容:
public static int CountUntyped(this IEnumerable source) {
int count = 0;
foreach(object obj in source) { count++; }
return count;
}
IEnumerable<T> source = ...
Assert.AreEqual(typed.Count(), source.CountUntyped());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.