I suspect the answer is no, but I'll ask anyway...
TL;DR
I know I can exclude a class or method from coverage analysis with the [ExcludeFromCodeCoverage]
attribute, but is there a way to exclude only part of a method?
Concrete example
I have a method that lazily generates a sequence of int.MaxValue
elements:
private static IEnumerable<TElement> GenerateIterator<TElement>(Func<int, TElement> generator)
{
for (int i = 0; i < int.MaxValue; i++)
{
yield return generator(i);
}
}
In practice, it's never fully enumerated, so the end of the method is never reached. Because of that, DotCover considers that 20% of the method is not covered, and it highlights the closing brace as uncovered (which corresponds to return false
in the generated MoveNext
method).
I could write a test that consumes the whole sequence, but it takes a very long time to run, especially with coverage enabled.
So I'd like to find a way to tell DotCover that the very last instruction doesn't need to be covered.
Note: I know I don't really need to have all the code covered by unit tests; some pieces of code can't or don't need to be tested, and I usually exclude those with the [ExcludeFromCodeCoverage]
attribute. But I like to have 100% reported coverage for the code that I do test, because it makes it easier to spot untested parts of the code. Having a method with 80% coverage when you know there is nothing more to test in it is quite annoying...
int.MaxValue
when you test with something manageable, unless that value is actually relevant somehow. – Opinionreturn Enumerable.Range(0, int.MaxValue).Select(generator);
? EDIT: Essentially, you'd "pass the buck" of the iteration/yielding itself to the LINQ code which wouldn't be counted by code coverage. – BrandishexclusiveUpperBound
parameter to theGenerateIterator
method. The publicGenerate
method that calls it passesint.MaxValue
, and the test directly calls theGenerateIterator
(that I made internal) with another value. I think it's cleaner than mutable static state... Anyway, that solves the issue for this specific scenario, but not for the general case, so the question remains open ;) – Oireachtas