我有很多类似于以下课程的课程:
public class Foo
{
private readonly Ba _ba;
private Foo(Ba ba)
{
if (ba is null) throw new ArgumentNullException(ba);
_ba = ba;
}
}
在其他类的内部结构中,我将其称为Foo
的构造函数,但由于这是意料之外的,因此在每个构造函数调用中,ba
不是null
。
我为组合框架编写了许多测试方法,但是由于上述代码片段中的异常是新抛出的,所以我无法达到100%的代码覆盖率。
我看到以下选择:
Foo(null)
时,调试都会更加困难。[ExcludeFromCodeCoverage]
装饰构造函数:这将适用于当前的Foo(Ba)
实现,但是只要我可能更改实现,构造函数中的新代码路径就可以开发并意外错过测试。您将如何解决困境?
该代码示例是用C#编写的,但该问题可能会解决一般的单元测试/异常处理问题。
C#8可以通过introducing non-nullable reference types解决此问题,但是我一直在寻找一个好的解决方案,直到它稳定发布为止。
答案 0 :(得分:2)
You have missed the most important alternative: Don't see it as a desirable goal to achieve 100% code coverage.
The robustness checks in your code are, strictly speaking, not testable in a sensible way. This will happen in various other parts of your code as well - it often happens in switch statements where all possible cases are explicitly covered and an extra default case is added just to throw an exception or otherwise handle this 'impossible' situation. Or, think of assertion statements added to the code: Since assertions should never fail, you will strictly speaking never be able to cover the else
branch that is hidden inside the assertion statement - how do you test that the expression inside the assertion is good to actually detect the problem you want it to?
Removing such robustness code and assertions is not a good idea, because they also protect you from undesired side effects of future changes. Excluding code from coverage analysis might be acceptable for the examples you have shown, but in most of the cases I have mentioned it would not be a good option. In the end you will have to make an informed decision (by looking at the coverage report in detail, not only the overall percentage) which statements/branches etc. of your code really need to be covered and which not.
And, as a final note, be aware that a high code coverage is not necessarily an indication that your test suite has a high quality. Your test suite has a high quality if it will detect the bugs in the code that could likely exist. You can have a test suite with 100% coverage that will not detect any of the potential bugs.