单元测试中用于检查代码覆盖率的反思
这是场景。我有 VO(值对象)或 DTO 对象,它们只是数据的容器。当我将它们分开并保存到数据库(由于很多原因)无法优雅地映射到 VO 时,我想测试每个字段是否已在数据库中成功创建并成功读回重建 VO。
有没有办法可以测试我的测试是否涵盖了 VO 中的每个字段?我有一个关于使用反射来迭代 VO 字段作为解决方案的一部分的想法,但也许你们之前已经解决了这个问题?
当我在 VO 中添加字段时,我希望此测试失败,并且不记得在测试中添加对其的检查。
开发环境: 使用 JUnit、Hibernate/Spring 和 Eclipse
Here's the scenario. I have VO (Value Objects) or DTO objects that are just containers for data. When I take those and split them apart for saving into a DB that (for lots of reasons) doesn't map to the VO's elegantly, I want to test to see if each field is successfully being created in the database and successfully read back in to rebuild the VO.
Is there a way I can test that my tests cover every field in the VO? I had an idea about using reflection to iterate through the fields of the VO's as part of the solution, but maybe you guys have solved the problem before?
I want this test to fail when I add fields in the VO, and don't remember to add checks for it in my tests.
dev environment:
Using JUnit, Hibernate/Spring, and Eclipse
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
保持简单:为每个 VO/DTO 编写一个测试:
生产性代码将会发展,并且也需要维护测试。恕我直言,使测试尽可能简单,即使它们是重复的,也是最好的方法。 过度设计测试或测试框架本身以使测试通用(例如,通过反射读取字段并自动填充 VO/DTO)会导致几个问题:
测试和生产代码本质上非常不同。在生产代码中,您尝试避免重复并最大限度地重用。生产代码可能很复杂,因为它是经过测试的。另一方面,您应该尝试尽可能简单地进行测试,并且重复是可以的。如果重复的部分被破坏,测试无论如何都会失败。
当生产代码发生更改时,可能需要对多个测试进行轻微更改。问题是测试被视为无聊代码。但我认为他们就应该这样。
如果我问错了你的问题,请告诉我。
Keep it simple: write one test per VO/DTO:
Productive code will evolve and tests will need to be maintained as well. Making tests the simplest as possible, even if they are repetitive, is IMHO the best approach. Over-engineering the tests or testing framework itself to make tests generic (e.g. by reading fields with reflection and filling VO/DTO automatically) leads to several problems:
Test and productive code are very different in nature. In productive code, you try to avoid duplication and maximize reuse. Productive code can be complicated, because it is tested. On the other hand, you should try to have tests as simple as possible, and duplication is ok. If a duplicated portion is broken, the test will fail anyway.
When productive code change, this may require several tests to be trivially changed. With the problem that tests are seen as boring piece of code. But I think that's the way they should be.
If I however got your question wrong, just let me know.
我建议使用 cobertura 来完成此任务。
运行测试后,您将获得完整的代码覆盖率报告,如果您使用
cobertura-check
ant 任务,您可以添加覆盖率检查并使用属性haltonfailure< 停止 ant 调用/代码>。
I would recommend cobertura for this task.
You will get a complete code coverage report after you run your tests and if you use the
cobertura-check
ant task you can add checks for the coverage and stop the ant call with the propertyhaltonfailure
.您可以将其作为
VO
验证的一部分。如果在使用 getter 时未设置字段,则可能会引发异常。You could make it part of the validation of the
VO
. If the fields aren't set when you use a getter it can throw an exception.