一个“单位"应该是什么?是什么时候进行单元测试? [英] What should a "unit" be when unit testing?

查看:32
本文介绍了一个“单位"应该是什么?是什么时候进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天在 Proggit 上,我正在阅读题为为什么单元测试是浪费时间".

On Proggit today I was reading the comment thread on a submission entitled, "Why Unit Testing Is A Waste of Time".

我并不真正关心文章的前提,而是关心 评论:

I'm not really concerned with premise of the article so much as I am with a comment made concerning it:

问题的根源在于商业软件中的大多数代码单元"项目很琐碎.

改变单位的大小,直到它不再琐碎?谁他妈的将代码单元定义为单个无论如何都是函数或方法!?

Change the size of the unit until it is no longer trivial? Who the hell defined the unit of code as a single function or method anyway!?

嗯,我合作过的一些人想将一个单位定义为单个职能.这完全是愚蠢的.我最喜欢的单位"定义是:最小的一段代码可以进行有用的测试.

Well, some of the guys I worked with wanted to define a unit as single functions. It was completely stupid. My favorite definition of "unit" is: the smallest piece of the code that can be usefully tested.

我们是否花了太多时间只是为了模拟一些对象并测试一段微不足道的代码而没有真正增加任何价值?

Are we spending too much time just to Mock out some objects and test a trivial piece of code and not really adding anything of value?

单元测试时单元"应该是什么?功能级别测试是否过于细化?

What should a "unit" be when Unit Testing? Are function level tests too granular?

推荐答案

引用 Wikipedia,但我认为在这种情况下它非常简洁准确:

It may seem trivial to quote Wikipedia, but I think it's very succinct and accurate in this case:

单元是应用程序中最小的可测试部分.

A unit is the smallest testable part of an application.

这似乎与您问题中的评论一致,即单元是可以进行有用测试的最小代码段".换句话说,使单元尽可能小这样它本身对开发人员/测试人员仍然有意义.

This seems to agree with the comment in your question that a unit is "the smallest piece of the code that can be usefully tested". In other words, make the unit as small as you possibly can such that it still makes sense to the developer/tester by itself.

通常,您希望单独测试项目的各个部分,然后测试它们如何组合交互.拥有不同层次(级别)的单元测试通常是明智之举,因为它有助于确保您的代码在所有级别(从单个功能到整个独立任务)都能正常工作.我个人不认为测试单个函数是错误的,甚至是无益的,只要它们本身在做一些有用的事情,通常情况就是如此.

Often you will want to test parts of a project in isolation, and then test how they interact in combination. Having various tiers (levels) of unit testing is often a wise thing to do, as it helps insure that your code is working as it should on all levels, from individual functions up to entire self-contained tasks. I personally do not believe that it is wrong, or even unhelpful, to test individual functions, so long as they are doing something useful in themselves, which can often be the case.

老实说,单元测试"中对单元"没有明确或严格的定义,这正是使用模糊术语单元"的原因!了解需要测试的内容和级别是经验问题,而且通常只是反复试验.这听起来可能有点不令人满意,但我相信这是一个合理的规则.

To be quite honest, there is no definite or rigorous definition of a "unit" in "unit testing", which is precisely why the vague term "unit" is used! Learning what needs to be tested and at what level is a matter of experience, and quite often, simply trial and error. It may sound like a slightly unsatisfying answer, but I believe it is a sound rule to follow.

这篇关于一个“单位"应该是什么?是什么时候进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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