JUnit best practices
JUnit is a typical toolkit: if used with care and with recognition of its idiosyncrasies, JUnit will help to develop good, robust tests. Used blindly, it may produce a pile of spaghetti instead of a test suite. This article presents some guidelines that can help you avoid the pasta nightmare. The guidelines sometimes contradict themselves and each other -- this is deliberate. In my experience, there are rarely hard and fast rules in development, and guidelines that claim to be are misleading.
We'll also closely examine two useful additions to the developer's toolkit:
- A mechanism for automatically creating test suites from classfiles in part of a filesystem
- A new
TestCase
that better supports tests in multiple threads
When faced with unit testing, many teams end up producing some kind of testing framework. JUnit, available as open source, eliminates this onerous task by providing a ready-made framework for unit testing. JUnit, best used as an integral part of a development testing regime, provides a mechanism that developers can use to consistently write and execute tests. So, what are the JUnit best practices?
测试遗留代码
/* I have no idea how this works but it seems to. Whatever you do, don't touch this function, and don't break this code! (虽然我不知道这段代码起什么作用,但是看上去它似乎是有用的。无论您做什么,一定不要碰这个函数, 不要破坏这段代码!) */
如果您曾经遇到过带有此类注释的代码,这种情况并不少见。因为没有人了解这些系统, 所以有时候就使用规则约束禁止进入整个系统;但是仍然需要对这些系统进行维护。即使是 一个已经完全没有 bug 的系统(又有哪个系统能够完全没有 bug?), 外部环境的改变也会使代码的改变成为必要。Y2K 营业额是一个最大且最明显的例子。欧元的引入对于某些金融系统来说相当于造成外伤。Sarbanes-Oxley 引入了新的以前不存在的报告要求,而且为了支持这些新规则,必须对遗留软件进行翻新。这个世界不是静态的,所以软件也不能是静态的,它必须向前发展否则就 会被代替。
好消息是,测试驱动开发不仅仅适合于新代码。即使是程序员维护老代码时也可以 利用它编写、运行以及通过测试。对于已经在生产中的遗留系统,测试确实更加 重要。只有通过测试,您才能确信您对于系统中的某一部分所做的改变不会中断其他地方的另外一部分。当然,您可能没有时间或者经费为一个规模庞大的代码基础达到 100% 的测试覆盖率,但是即使是并不完美的覆盖率也能减少失败的风险,加速开发并且产生更加健壮的代码。