我看到很多问题都在问“如何”用一种特定的语言进行单元测试,但没有人问“什么”、“为什么”和“什么时候”。

是什么? 它对我有什么用? 我为什么要用它? 什么时候用(什么时候不用)? 有哪些常见的陷阱和误解


单元测试,粗略地说,就是在与测试代码隔离的情况下测试代码。我想到的直接优势是:

测试的运行变得自动化和可重复 您可以在更细粒度的级别上进行测试,而不是通过GUI进行点击测试

请注意,如果您的测试代码写入文件、打开数据库连接或在网络上执行某些操作,则更适合将其归类为集成测试。集成测试是一件好事,但不应将其与单元测试混淆。单元测试代码应该简短、简单且易于执行。

另一种看待单元测试的方法是先编写测试。这被称为测试驱动开发(简称TDD)。TDD带来了额外的优势:

您不需要编写推测性的“我将来可能需要这个”代码——只要能够通过测试即可 您编写的代码总是会被测试覆盖 通过先编写测试,您不得不考虑如何调用代码,从长远来看,这通常会改善代码的设计。

如果你现在还没有做单元测试,我建议你现在就开始做。找一本好书,实际上任何xUnit-book都可以,因为它们之间的概念可以很好地转换。

有时编写单元测试会很痛苦。当出现这种情况时,试着找个人来帮助你,并抵制住“只写该死的代码”的诱惑。单元测试很像洗碗。这并不总是令人愉快的,但它让你的比喻厨房保持干净,而你真的希望它干净。:)


编辑:我想到了一个误解,虽然我不确定它是否普遍。我曾听一个项目经理说过,单元测试让团队把所有的代码都写了两次。如果它看起来和感觉是那样的,那么,你做错了。编写测试通常不仅可以加快开发速度,而且还为您提供了一个方便的“现在我完成了”指示器,否则您就不会有这个指示器。


我不反对丹的观点(尽管不回答可能是更好的选择)……但是……

单元测试是编写代码来测试系统的行为和功能的过程。

显然,测试可以提高代码的质量,但这只是单元测试的表面好处。真正的好处是:

Make it easier to change the technical implementation while making sure you don't change the behavior (refactoring). Properly unit tested code can be aggressively refactored/cleaned up with little chance of breaking anything without noticing it. Give developers confidence when adding behavior or making fixes. Document your code Indicate areas of your code that are tightly coupled. It's hard to unit test code that's tightly coupled Provide a means to use your API and look for difficulties early on Indicates methods and classes that aren't very cohesive

你应该进行单元测试,因为向客户交付可维护的高质量产品符合你的利益。

我建议您将它用于任何系统,或系统的一部分,以模拟真实世界的行为。换句话说,它特别适合于企业开发。我不会将它用于一次性/实用程序。我不会用它来测试系统中有问题的部分(UI是一个常见的例子,但并不总是这样)

最大的陷阱是开发人员测试太大的单元,或者他们认为一个方法是一个单元。如果您不理解控制反转,这一点尤其正确——在这种情况下,您的单元测试总是会变成端到端集成测试。单元测试应该测试单个行为——大多数方法都有许多行为。

最大的误解是程序员不应该测试。只有糟糕或懒惰的程序员才会相信这一点。给你盖屋顶的人不应该测试吗?更换心脏瓣膜的医生不应该检查新瓣膜吗?只有程序员才能测试他的代码是否按照他的意图去做(QA可以测试边缘情况——当代码被告知要做程序员不打算做的事情时,它的行为如何,而客户可以进行验收测试——代码是否按照客户的要求去做)


This is my take on it. I would say unit testing is the practice of writing software tests to verify that your real software does what it is meant to. This started with jUnit in the Java world and has become a best practice in PHP as well with SimpleTest and phpUnit. It's a core practice of Extreme Programming and helps you to be sure that your software still works as intended after editing. If you have sufficient test coverage, you can do major refactoring, bug fixing or add features rapidly with much less fear of introducing other problems.

当所有单元测试都能自动运行时,这是最有效的。

单元测试通常与OO开发相关联。基本思想是创建一个脚本,为你的代码设置环境,然后练习它;您编写断言,指定您应该接收的预期输出,然后使用如上所述的框架执行您的测试脚本。

框架将针对您的代码运行所有测试,然后报告每个测试的成功或失败。phpUnit默认情况下从Linux命令行运行,尽管有HTTP接口可用于它。SimpleTest本质上是基于web的,在我看来,它更容易启动和运行。结合xDebug, phpUnit可以为您提供代码覆盖率的自动统计数据,有些人认为这非常有用。

有些团队从他们的subversion存储库编写钩子,以便在提交更改时自动运行单元测试。

将单元测试保存在与应用程序相同的存储库中是一个很好的实践。


单元测试是在不需要该代码单元所依赖的基础设施的情况下对代码单元(例如单个函数)进行测试。即在隔离环境中进行测试。

例如,如果您正在测试的函数连接到数据库并执行更新,那么在单元测试中您可能不想执行该更新。如果这是一个积分测试,你会这样做,但在这个例子中,它不是。

因此,单元测试将测试您正在测试的“函数”中所包含的功能,而不会产生数据库更新的副作用。

假设函数从数据库中检索了一些数字,然后执行标准偏差计算。你想测试什么?标准偏差计算正确,还是数据从数据库返回?

在单元测试中,您只想测试标准偏差的计算是否正确。在集成测试中,您希望测试标准偏差计算和数据库检索。


我在FoxForward 2007参加了一个关于单元测试的演讲,被告知永远不要对任何与数据相关的东西进行单元测试。毕竟,如果您在实时数据上进行测试,结果是不可预测的,如果您不在实时数据上进行测试,那么实际上并不是在测试您所编写的代码。不幸的是,这是我最近编写的大部分代码。: -)

最近,当我编写一个保存和恢复设置的例程时,我确实尝试了TDD。首先,我验证了是否可以创建存储对象。然后,它有我需要调用的方法。然后,我可以称之为。然后,我可以给它传递参数。然后,我可以给它传递特定的参数。依此类推,直到我最终验证它将保存指定的设置,允许我更改它,然后为几种不同的语法恢复它。

我没看完,因为我现在需要例行公事,但这是一个很好的练习。


如果给你一堆垃圾,你似乎陷入了一种永久的清理状态,你知道任何新功能或代码的添加都会破坏当前的设置,因为当前的软件就像一个纸牌屋,你会怎么做? 那么我们如何进行单元测试呢?

从小事开始。我刚加入的项目直到几个月前才开始进行单元测试。当覆盖率如此之低时,我们将简单地选择一个没有覆盖率的文件并单击“添加测试”。

现在我们已经达到了40%以上,我们已经成功地摘走了大部分容易摘到的果实。

(最好的部分是,即使在这样低的覆盖率水平上,我们已经遇到了许多代码做错误事情的实例,并且测试发现了它。这是促使人们增加更多测试的巨大动力。)


在单元测试和TDD的哲学优势方面,这里有一些关键的“灯泡”观察,这些观察在我试探性地走上TDD启蒙之路的第一步时打动了我(没有原创或一定是新闻)……

TDD does NOT mean writing twice the amount of code. Test code is typically fairly quick and painless to write and is a key part of your design process and critically. TDD helps you to realize when to stop coding! Your tests give you confidence that you've done enough for now and can stop tweaking and move on to the next thing. The tests and the code work together to achieve better code. Your code could be bad / buggy. Your TEST could be bad / buggy. In TDD you are banking on the chances of BOTH being bad / buggy being fairly low. Often its the test that needs fixing but that's still a good outcome. TDD helps with coding constipation. You know that feeling that you have so much to do you barely know where to start? It's Friday afternoon, if you just procrastinate for a couple more hours... TDD allows you to flesh out very quickly what you think you need to do, and gets your coding moving quickly. Also, like lab rats, I think we all respond to that big green light and work harder to see it again! In a similar vein, these designer types can SEE what they're working on. They can wander off for a juice / cigarette / iphone break and return to a monitor that immediately gives them a visual cue as to where they got to. TDD gives us something similar. It's easier to see where we got to when life intervenes... I think it was Fowler who said: "Imperfect tests, run frequently, are much better than perfect tests that are never written at all". I interprete this as giving me permission to write tests where I think they'll be most useful even if the rest of my code coverage is woefully incomplete. TDD helps in all kinds of surprising ways down the line. Good unit tests can help document what something is supposed to do, they can help you migrate code from one project to another and give you an unwarranted feeling of superiority over your non-testing colleagues :)

这篇演讲很好地介绍了测试所需要的所有内容。


测试驱动开发在某种程度上取代了单元测试这个术语。作为一个老手,我会提到它的更一般的定义。

单元测试还意味着测试一个较大系统中的单个组件。这个组件可以是dll、exe、类库等。它甚至可以是多系统应用程序中的单个系统。因此,单元测试最终是对一个更大系统的单个部分进行测试。

然后,您可以通过测试所有组件如何一起工作来进行集成测试或系统测试。


我使用单元测试来节省时间。

在构建业务逻辑(或数据访问)时,测试功能通常涉及在许多屏幕上输入内容,这些内容可能尚未完成,也可能尚未完成。自动化这些测试可以节省时间。

对我来说,单元测试是一种模块化的测试工具。每个公共函数通常至少有一个测试。我编写额外的测试来覆盖各种行为。

您在开发代码时想到的所有特殊情况都可以记录在单元测试的代码中。单元测试还成为如何使用代码的示例的来源。

对我来说,在单元测试中发现我的新代码破坏了某些东西比检入代码并让前端开发人员发现问题要快得多。

对于数据访问测试,我尝试编写没有更改或自行清理的测试。

单元测试不能解决所有的测试需求。他们将能够节省开发时间并测试应用程序的核心部分。


使用Testivus。你需要知道的都在那里:)


我在大学里从未学过单元测试,我花了一段时间才“学会”它。我读到它,心想“啊,对,自动化测试,我想那应该很酷”,然后我就忘记了。

It took quite a bit longer before I really figured out the point: Let's say you're working on a large system and you write a small module. It compiles, you put it through its paces, it works great, you move on to the next task. Nine months down the line and two versions later someone else makes a change to some seemingly unrelated part of the program, and it breaks the module. Worse, they test their changes, and their code works, but they don't test your module; hell, they may not even know your module exists.

现在你有了一个问题:坏代码在主干中,甚至没有人知道。最好的情况是内部测试人员在您发布之前就发现了它,但是在游戏后期修复代码的成本很高。如果没有内部测试人员发现它……嗯,这确实会非常昂贵。

The solution is unit tests. They'll catch problems when you write code - which is fine - but you could have done that by hand. The real payoff is that they'll catch problems nine months down the line when you're now working on a completely different project, but a summer intern thinks it'll look tidier if those parameters were in alphabetical order - and then the unit test you wrote way back fails, and someone throws things at the intern until he changes the parameter order back. That's the "why" of unit tests. :-)


单元测试是关于编写测试应用程序代码的代码。

名称的Unit部分是关于一次测试小单元代码(例如一个方法)的意图。

xUnit是用来帮助测试的——它们是帮助测试的框架。其中一部分是自动测试运行器,它会告诉您哪些测试失败,哪些测试通过。

它们还可以在每个测试之前设置您需要的公共代码,并在所有测试完成后将其删除。

您可以使用一个测试来检查是否抛出了预期的异常,而不必自己编写整个try catch块。


单元测试与“只是打开一个新项目并测试这个特定的代码”的主要区别在于它是自动化的,因此是可重复的。

如果您手动测试代码,它可能会使您相信代码在当前状态下工作得很完美。但一周后,当你对它做了轻微的修改时呢?您是否愿意在代码发生任何更改时再次手工重新测试?很可能不会:-(

但是,如果您可以在任何时间运行您的测试,只需单击一下,以完全相同的方式,在几秒钟内,那么一旦有什么东西坏了,它们就会立即显示给您。如果您还将单元测试集成到您的自动化构建过程中,即使在看似完全无关的更改破坏了代码库中遥远部分的某些情况下,它们也会提醒您错误——当您甚至不会想到需要重新测试特定的功能时。

这是单元测试相对于手工测试的主要优势。但等等,还有更多:

unit tests shorten the development feedback loop dramatically: with a separate testing department it may take weeks for you to know that there is a bug in your code, by which time you have already forgotten much of the context, thus it may take you hours to find and fix the bug; OTOH with unit tests, the feedback cycle is measured in seconds, and the bug fix process is typically along the lines of an "oh sh*t, I forgot to check for that condition here" :-) unit tests effectively document (your understanding of) the behaviour of your code unit testing forces you to reevaluate your design choices, which results in simpler, cleaner design

反过来,单元测试框架使您更容易编写和运行测试。


单元测试是一种实践,以确保您将要实现的功能或模块的行为符合预期(需求),并确保它在边界条件和无效输入等场景下的行为。

xUnit, NUnit, mbUnit等都是帮助你编写测试的工具。


如果你想使用Kent Beck推广的TDD方法开发项目,像NUnit、xUnit或JUnit这样的库是必须的:

你可以阅读《测试驱动开发介绍》(TDD)或Kent Beck的《测试驱动开发:举例说明》。

然后,如果你想确保你的测试覆盖了代码中“好的”部分,你可以使用NCover、JCover、PartCover或其他软件。它们会告诉你代码的覆盖率。取决于你对TDD的熟练程度,你会知道你是否已经很好地练习了它:)


首先,无论是谈论单元测试还是其他类型的自动化测试(集成、加载、UI测试等),与您所建议的关键区别在于它是自动化的、可重复的,并且不需要消耗任何人力资源(=没有人需要执行测试,它们通常按下按钮就可以运行)。


I think the point that you don't understand is that unit testing frameworks like NUnit (and the like) will help you in automating small to medium-sized tests. Usually you can run the tests in a GUI (that's the case with NUnit, for instance) by simply clicking a button and then - hopefully - see the progress bar stay green. If it turns red, the framework shows you which test failed and what exactly went wrong. In a normal unit test, you often use assertions, e.g. Assert.AreEqual(expectedValue, actualValue, "some description") - so if the two values are unequal you will see an error saying "some description: expected <expectedValue> but was <actualValue>".

总之,单元测试将使测试更快,对开发人员来说更舒服。您可以在提交新代码之前运行所有的单元测试,这样就不会中断同一项目中其他开发人员的构建过程。


我想推荐Gerard Meszaros的《xUnit测试模式》一书。它很大,但在单元测试方面是一个很好的资源。这里有一个链接到他的网站,在那里他讨论了单元测试的基础知识。http://xunitpatterns.com/XUnitBasics.html


这回答了为什么您应该进行单元测试。


下面的三个视频涵盖了javascript中的单元测试,但一般原则适用于大多数语言。

单元测试:现在的几分钟将节省几小时后- Eric Mann - https://www.youtube.com/watch?v=_UmmaPe8Bzc

JS单元测试(非常好)- https://www.youtube.com/watch?v=-IYqgx8JxlU

编写可测试的JavaScript - https://www.youtube.com/watch?v=OzjogCFO4Zo


Now I'm just learning about the subject so I may not be 100% correct and there's more to it than what I'm describing here but my basic understanding of unit testing is that you write some test code (which is kept separate from your main code) that calls a function in your main code with input (arguments) that the function requires and the code then checks if it gets back a valid return value. If it does get back a valid value the unit testing framework that you're using to run the tests shows a green light (all good) if the value is invalid you get a red light and you then can fix the problem straight away before you release the new code to production, without testing you may actually not have caught the error.

So you write tests for you current code and create the code so that it passes the test. Months later you or someone else need to modify the function in your main code, because earlier you had already written test code for that function you now run again and the test may fail because the coder introduced a logic error in the function or return something completely different than what that function is supposed to return. Again without the test in place that error might be hard to track down as it can possibly affect other code as well and will go unnoticed.


Also the fact that you have a computer program that runs through your code and tests it instead of you manually doing it in the browser page by page saves time (unit testing for javascript). Let's say that you modify a function that is used by some script on a web page and it works all well and good for its new intended purpose. But, let's also say for arguments sake that there is another function you have somewhere else in your code that depends on that newly modified function for it to operate properly. This dependent function may now stop working because of the changes that you've made to the first function, however without tests in place that are run automatically by your computer you will not notice that there's a problem with that function until it is actually executed and you'll have to manually navigate to a web page that includes the script which executes the dependent function, only then you notice that there's a bug because of the change that you made to the first function.

重申一下,在开发应用程序时运行测试将在编写代码时发现这类问题。如果没有适当的测试,你必须手动检查整个应用程序,即使这样也很难发现错误,你天真地将其发送到生产环境中,一段时间后,好心的用户会给你发送错误报告(这不会像你在测试框架中的错误消息那样好)。


It's quite confusing when you first hear of the subject and you think to yourself, am I not already testing my code? And the code that you've written is working like it is supposed to already, "why do I need another framework?"... Yes you are already testing your code but a computer is better at doing it. You just have to write good enough tests for a function/unit of code once and the rest is taken care of for you by the mighty cpu instead of you having to manually check that all of your code is still working when you make a change to your code.

此外,如果你不想进行单元测试,你也不必进行单元测试,但随着你的项目/代码库开始变得越来越大,引入错误的可能性也在增加,这是值得的。


单元测试和TDD通常能让你对所编写的软件有更短的反馈周期。与在实现的最后有一个大型测试阶段不同,您可以增量地测试您所编写的所有内容。这大大提高了代码质量,正如您立即看到的那样,您可能会有错误。