我正致力于将单元测试集成到我所在团队的开发过程中,有一些人对此持怀疑态度。有什么好方法可以让团队中持怀疑态度的开发人员相信单元测试的价值?在我的具体情况下,我们将在添加功能或修复错误时添加单元测试。不幸的是,我们的代码库并不容易进行测试。


当前回答

根据我的经验,在复杂的软件环境中,单元测试和集成测试是“必须的”。

为了说服团队中的开发人员编写单元测试,您可能需要考虑在开发环境中集成单元测试回归分析(例如,在您的日常构建过程中)。

一旦开发人员知道如果单元测试失败,他们就不必花那么多时间调试它来发现问题,他们就会更有动力去编写这些测试。

这里有一个工具可以提供这样的功能:

单元测试回归分析工具

其他回答

单元测试的全部意义在于使测试变得简单。这是自动的。“make test”就完成了。如果您面临的问题之一是难以测试代码,那么这就是使用单元测试的最佳理由。

我曾多次尝试单元测试,我仍然相信,考虑到我的情况,这是值得的。

我开发网站,其中很多逻辑涉及在数据库中创建、检索或更新数据。当我为了单元测试的目的而尝试“模拟”数据库时,它变得非常混乱,似乎有点毫无意义。

当我围绕业务逻辑编写单元测试时,从长远来看它从未真正帮助过我。因为我主要独自从事项目工作,我倾向于直观地知道哪些代码区域可能会受到我所从事的工作的影响,并且我手动测试这些区域。我希望尽可能快地向客户交付解决方案,而单元测试通常看起来是浪费时间。我列出了手动测试,并亲自完成它们,并在执行过程中标记它们。

我可以看到,当一个开发团队在一个项目中工作并互相更新代码时,这可能是有益的,但即使这样,我认为如果开发人员具有高质量,良好的沟通和编写良好的代码通常就足够了。

Unit Testing is one of the most adopted methodologies for high quality code. Its contribution to a more stable, independent and documented code is well proven . Unit test code is considered and handled as an a integral part of your repository, and as such requires development and maintenance. However, developers often encounter a situation where the resources invested in unit tests where not as fruitful as one would expect. In an ideal world every method we code will have a series of tests covering it’s code and validating it’s correctness. However, usually due to time limitations we either skip some tests or write poor quality ones. In such reality, while keeping in mind the amount of resources invested in unit testing development and maintenance, one must ask himself, given the available time, which code deserve testing the most? And from the existing tests, which tests are actually worth keeping and maintaining? See here

最好的说服方式是……找到一个bug,为它写一个单元测试,修复这个bug。

这个特定的错误不太可能再次出现,您可以通过测试来证明它。

如果你做得足够多,其他人很快就会明白。

单元测试很像去健身房。你知道这对你有好处,所有的争论都有意义,所以你开始锻炼。刚开始有一种冲动,这很好,但几天后你开始怀疑是否值得这样做。你每天花一个小时换衣服,在仓鼠转轮上跑步,你不确定除了腿和手臂疼痛之外,你真的得到了什么。

然后,也许一两周后,就在疼痛消失的时候,一个重要的截止日期开始来临。你需要把醒着的每一个小时都用来完成“有用的”工作,所以你要去掉无关紧要的事情,比如去健身房。你改掉了这个习惯,当截止日期结束的时候,你又回到了起点。如果你设法回到健身房,你会觉得和你第一次去的时候一样酸痛。

You do some reading, to see if you're doing something wrong. You begin feel a little bit of irrational spite toward all the fit, happy people extolling the virtues of exercise. You realize that you don't have a lot in common. They don't have to drive 15 minutes out of the way to go to the gym; there is one in their building. They don't have to argue with anybody about the benefits of exercise; it is just something everybody does and accepts as important. When a Big Deadline approaches, they aren't told that exercise is unnecessary any more than your boss would ask you to stop eating.

所以,回答你的问题,单元测试通常是值得付出努力的,但是所需的努力量对每个人来说都不一样。如果你在一家不重视代码质量的公司处理意大利面条式的代码库,那么单元测试可能需要付出巨大的努力。(许多经理会歌颂单元测试,但这并不意味着他们会在关键时刻支持单元测试。)

如果你正试图将单元测试引入到你的工作中,并且没有看到你所期待的所有阳光和彩虹,不要责怪自己。你可能需要找一份新工作来真正让单元测试为你工作。