软件开发的单元测试要有选择性

软件开发的单元测试是IT业界的新宗教,尤其对于软件开发人员。

但是软件开发的单元测试是不是一必需的呢?对于算法及通用的库类,单元测试可能是需要的。

但你为什么要测试SpringMVC Controllers呢?

单元测试保守估计,可能普遍要占到开发时间的20%以上,这还不算build/release所耗费的时间。有多少问题是通过单元测试来发现的呢?太少了,个人经验几乎为零。单元测试的投入与效果相差太大了,太不划算了。

根本原因,是单元测试几乎不能发现问题。为什么呢?TDD推荐先写单元测试,再写应用代码,但这与人类的行为习惯是格格不入的。因此单元测试一般是在开发人员将程序写好后补加的。因此绝大多数的单元测试是对程序代码的简单机械的重复。如果开发人员在写程序时漏掉了什么条件或某种情形,单元测试也不可能测到,因为单元测试一般是由这同一个开发人员写的测试。因为单元测试是新宗教,大家都强调,大家都写,他迫不得已也写单元测试,如此而已。因此绝大多数的单元测试,只是同一个开发人员的应用代码的简单重复而已,纯粹浪费时间。可以说单元测试是最标准的 “Repeat yourself”。

对于大多数应用,尤其是网络应用,单元测试非但发现不了任何问题,相反,单元测试占用了开发人员大量的宝贵时间。如果有问题,开发人员不但要解决应用中的问题,还要同时解决相关的单元测试。本人见过极其复杂的单元测试,甚至比它要测试的应用代码还要复杂,这简直是颠倒本末。

单元测试是TDD的产物,就像宗教一样,谁都不敢反对。但本文以为单元测试不是必需的,单元测试必须根据具体情况而决定其必要性。

真正有意义的是Integration/System Test and Regression Test。这两种测试能有效帮助开发人员发现问题,因为这两种测试最接近生产环境。Mocking is not real.

Unit tests test the application code. It cannot test the logics the application code fails to cover. Thus unit test is merely a repeat of what the developer thinks the application code should be. That's why unit test rarely find problems at all. Unit test is the real and biggest "Repeat yourself".

When you change your application, unit tests might fail and you not only change your application code, you fix the unit test as well.

TDD promotes writing unit test first and then your application. But in real life that rarely happens as well, since it's not only anti-pattern, it's just not what human being manner of doing things. Most, if not 100% , developers write the application code and add the unit test for it when everything looks like working. 

One should value integration test and automated regression test. Unit test in most cases is merely political and a waste of time.

猜你喜欢

转载自jxee.iteye.com/blog/2178789