简体   繁体   English

编写JUnit测试用例的最佳规则

[英]Best rules to write JUnit test cases

We have a project with > 80% test coverage but the quality of the code is still a problem. 我们有一个测试覆盖率> 80%的项目,但是代码的质量仍然是一个问题。 Some changes will bring in new bugs ever with test cases to cover the logic. 某些更改将带来测试用例涵盖逻辑的新错误。 What's the best rules to write the JUnit test cases? 编写JUnit测试用例的最佳规则是什么?

  • A tip first: when developing new code, start doing it in a unit test 首先提示:开发新代码时,请在单元测试中开始做
  • Do not start with border cases, null tests 不要从边界情况开始,测试为空
  • Make stable tests, which will not easily be broken with source changes 进行稳定的测试,这些测试不会随源变更而轻易中断
  • For scenarios with business data, sequences, make help functions 对于具有业务数据,序列的业务情景,请创建帮助功能
  • Catching regression errors, weakness in the code usage is the main goal 捕获回归错误,代码使用方面的弱点是主要目标
  • New code often merits to be redesigned, a rewrite when some additional functionality crystallizes. 新代码通常值得重新设计,当一些其他功能具体化时就需要重写。 A unit test should not be a burdon, and be entirely rewritten too 单元测试不应该是一种负担,也应该完全重写

Some effort can better go into the tested code. 一些努力可以更好地进入经过测试的代码。 100% coverage also implies that much effort went into test code and its maintenance. 100%的覆盖率还意味着测试代码及其维护需要投入大量精力。

However if a unit test of a source is cumbersome, refactor the original code by splitting responsibilities. 但是,如果对源进行单元测试很麻烦,请通过划分职责来重构原始代码。 This can be done ugly by using inheritance for separating different aspects. 通过使用继承来分隔不同方面,可能很难做到这一点。

Rely on findbugs/coverity, selenium and such too. 也依赖findbugs / coverity,硒等。

You said "Some changes will bring in new bugs ever with test cases to cover the logic". 您说“有些变更会带来测试用例所涉及的新错误,以涵盖逻辑”。 My question is what kind of bugs are introduced? 我的问题是引入了哪种错误? Are these functional bugs say missing a functionality or a functionality not working as expected even though the code and Unit test both are there. 这些功能性错误是否表示缺少功能或功能无法按预期运行,即使同时存在代码和单元测试也是如此。 Then I would say you need to do some requirement mapping. 然后我会说您需要做一些需求映射。 Junits are not only helpful to cover the "written code", but you should also look at the requirements/scenarios and there should be atleast one unit-test for each scenario. Junit不仅有助于涵盖“书面代码”,而且您还应该查看需求/方案,并且每种方案至少应有一个单元测试。 Every time there is a change in functionality, make sure you update/add the Junit first (so it will start failing), then update/add/remove code. 每次功能更改时,请确保先更新/添加Junit(这样它将开始失败),然后再更新/添加/删除代码。 So the failed Junit now start passing. 因此,失败的Junit现在开始通过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM