Cobertura覆盖和断言关键字 [英] Cobertura coverage and the assert keyword

查看:211
本文介绍了Cobertura覆盖和断言关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Cobertura测量的单元测试的线路覆盖范围正在受到影响,因为我有断言这些未在测试中涵盖的语句。我应该测试断言离子,有没有办法让Cobertura忽略它们,这样它们不会影响我的测试覆盖率?

My line coverage for unit tests measured by Cobertura is suffering, because I have assert statements which are not covered in tests. Should I be testing assertions, and is there any way to get Cobertura to ignore them so they do not affect my test coverage?

推荐答案

运行你的Java 断言语句的覆盖范围应该简单启用断言的测试套件,即将-ea作为jvm的参数。
如果你这样做,你会发现cobertura很容易报告100%的覆盖率,如果你的其余行也被覆盖。

The line coverage of your Java assert statements should be simply covered by running your test suite with assertions enabled, i.e., giving -ea as argument to the jvm. If you do this, you'll see that cobertura easily reports 100% line coverage if the rest of your lines are covered as well.

尽管如此,断言行仍将显示为红色,表明覆盖范围不足。
这是因为你的断言通常都是正确的,所以你永远不会碰到假分支。

Nevertheless, the assert lines will still be colored red, suggesting insufficient coverage. This is because your assertions are usually always true, so you never hit the false branch.

因此,使用断言,Cobertura中的 branch 报道搞砸了行将具有50%的分支覆盖率,使整个分支覆盖率难以解释(或无用)。

Thus, branch coverage in Cobertura is messed up by using assert, since assert lines will have 50% branch coverage, rendering the overall branch coverage percentage hard to interpret (or useless).

Clover 有一个很好的功能,可以在计算覆盖范围时忽略断言。我没有在任何开源Java覆盖工具中看到过这个功能。

Clover has a nice feature to ignore assert when computing coverage. I haven't seen this feature in any open source Java coverage tool.

如果你在按合同设计样式,不需要添加使Java 断言语句失败的测试。事实上,对于许多断言(例如,不变量,后置条件),
甚至无法创建会使其失败的对象,因此不可能来编写此类测试。
但是,您可以使用不变量/后置条件来导出行使其边界的测试用例 - 请参阅Robert Binder的不变边界模式。但这不会使你的断言失败。

If you use assertions in a design-by-contract style, there is no need to add tests that make your Java assert statements fail. As a matter of fact, for many assertions (e.g., invariants, post-conditions) you cannot even create objects that would make them fail, so it is impossible to write such tests. What you can do, though, is use the invariants/postconditions to derive test cases exercising their boundaries -- see Robert Binder's invariant boundaries pattern. But this won't make your assertions fail.

只有当你对给定方法有一个非常棘手的前提条件时,你可能要考虑编写一个针对特定方法的测试使前提条件失败。但是,重新思考你的先决条件可能是一个更好的主意。

Only if you have a very tricky pre-condition for a given method, you may want to consider writing a test aimed at making the pre-condition fail. But then re-thinking your pre-condition may be a better idea.

这篇关于Cobertura覆盖和断言关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆