Java 代码覆盖率的想法?
我正在开发一个 Java 项目,其中有一个 ant 构建,它运行 JUnit 测试,并由 Cobertura 监控。这非常有效,我们的覆盖率一直保持在很高的水平。对于某些类,例如 Hibernate 实体,我们在其中包含最少的代码,但具有 equals 和 hashCode 方法。测试这些是一个巨大的痛苦,并且会降低覆盖率。我们尝试使用 EqualsVerifier 两个类相互引用,这在 Hibernate 实体中经常发生。
我们考虑过使用 Commons EqualsBuilder,但随后我们失去了 IDE 自动生成 equals/hashCode 方法的能力。我知道 EqualsBuilder 也可以通过反射来完成,但我们不想仅仅为了构建时单元测试覆盖率而损失运行时性能。
理想的情况是,我们可以告诉 Cobertura 忽略 equals 和 hashCode 方法,但那里的补丁要求我们注释我们的类,这似乎有点尴尬。
因此,我希望从其他人那里得到关于在这种情况下有效的想法。有人对如何完成这项工作有任何想法吗?
谢谢!
I am working on a Java project where I have an ant build, which runs JUnit tests, which are monitored by Cobertura. That works great and we have kept our coverage very high. For some classes, like Hibernate entities, we have minimal code in them, but have equals and hashCode methods. Testing those is a huge pain, and drags down the coverage percentages. We've tried using EqualsVerifier two classes have references to each other, which occurs often in Hibernate entities.
We've considered using Commons EqualsBuilder, but then we lose the ability to have IDE's autogenerate the equals/hashCode methods. I know EqualsBuilder also can be done through reflection, but we don't want to lose runtime performance just for build-time unit test coverage.
An ideal situation would be if we could tell Cobertura to just ignore equals and hashCode methods, but the patches out there require us to annotate our classes, which seems a bit awkward.
So, I'm hoping for ideas from others as to what works well in such instances. Does anyone have any ideas for how to get this done?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我看来,您需要做出决定: equals 和 hashCode 都不重要,在这种情况下您应该忽略 < 100% 代码覆盖率指标(或找出如何忽略某个方法)。或者它们很重要,您应该编写单元测试来练习它们。这可能并不有趣,但听起来你很关心这些方法是否正常工作。在这种情况下,您可能需要测试它们。
It seems to me like you need to make a decision: Either equals and hashCode are not important, and in that event you should just ignore the < 100% code coverage metric (or figure out how to ignore a method). Or they are important, and you should write the unit tests to exercise them. It may not be fun, but it sounds like you care if these methods work properly. In which case, you probably need to test them.
如果不值得测试,那么一开始就可能不值得编写代码。
换句话说:如果您的 equals 和 hashcode 方法在生产代码中的任何位置使用,那么您需要代码覆盖率。就这么简单。否则会引起bug。相信我,它会。
顺便说一句,“测试这些是一个巨大的痛苦”永远不应该成为放弃测试的充分理由。现在巨大的痛苦通常意味着巨大的努力,但从长远来看是值得的。
If it's not worth testing, it's probably not worth writing the code in the first place.
In other words: if your equals and hashcode methods are used anywhere in your production code, then you need code coverage. As simple as that. Else it will cause bugs. Trust me, it will.
And by the way, "testing those is a huge pain" should never be a reason enough to give up testing. Huge pain usually translates as big effort now, but worth it in the long run.