什么是单元测试,我为什么要关心? [英] What are unit tests and why should I care?

查看:184
本文介绍了什么是单元测试,我为什么要关心?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我用PHP和JavaScript开发Web应用程序,很多时候在Stack Overflow上我已经看到了单元测试这个词,但我在网站上找不到任何地方对单元测试究竟是什么的满意答案。

Okay, I develop web applications in PHP and JavaScript and a lot of times here on Stack Overflow I have seen the word unit test passing by, but nowhere on the website have I been able to found a satisfactory answer to what exactly a unit test is.

那么什么是单元测试呢?作为PHP和JavaScript程序员,我应该关注,还是只针对真正的编程语言?

So what are unit tests and should I, as a PHP and JavaScript programmer, care, or are they only for 'real' programming languages?

推荐答案

单元测试适用于您希望维护的任何代码。

Unit tests are for any code you wish to maintain.

简而言之,想法是编写许多小测试,每个测试都可以独立运行,并测试代码库中最小的部分(通常是单个类或单个函数)。如果我给这个函数它预期的输入,它会返回我期望的输出吗?如果是这样,那意味着应用程序的其余部分几乎可以认为它有效。如果没有,我宁愿在一个小的,简单的,孤立的单元测试函数中捕获错误,而不是试图通过我的整个应用程序跟踪它。

In a nutshell, the idea is to write many small tests, each of which can be run in isolation, and test the smallest possible part of your codebase (often individual classes or individual functions). If I give this function the input it expects, does it return the output I expect? If it does, that means the rest of the application can pretty much assume it works. And if it doesn't, I'd rather catch the error in a small, simple, isolated unit test function than trying to trace it through the entirety of my application.

当然,它还要求您在编写代码方面要有相当的纪律,因为必须能够隔离单个函数或类来测试它们,并且因为测试不会自行编写。你必须这样做。 ;)

Of course, it also requires you to be fairly disciplined in how you write your code, both because it has to be possible to isolate individual functions or classes to test them, and because, well, the tests don't write themselves. You have to do that. ;)

鉴于我见过的大多数PHP代码的质量,我认为单元测试肯定是在PHP社区。事实上,比几乎任何其他语言都要多。 ;)

Given the quality of most of the PHP code I've seen, I'd say unit testing definitely has its place in the PHP community. More so than in almost any other language, in fact. ;)

这篇关于什么是单元测试,我为什么要关心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆