单元测试中的单元是啥意思?(每日一译)

What does the ‘unit’ in ‘unit test’ mean? (by Roy Osherove

I used to think it was a method. Then I thought it coule be several methods. then I thought it might be several classes. then I realized it changes all the time.

我曾经觉得这指的是一个方法,几个方法或者几个类,我的看法一直在变化着。

It means “unit of work”.

我现在觉得单元指的是工作单元。

A unit of work is a use case in the system, that is initiated by a public method somewhere, and ends up with an end result. An end result can be one of three things:

一个工作单元是系统中的一个用例,它常常开始于一个公共的方法,结束时伴随如下三种结果:

  • A return value(if the public method is a function) or an exception return value
  • 一个返回值(如果这个公共方法是个函数的话)或者抛出一个异常。
  • A noticeable change to the state of the system under test. Noticeablemeans that the system behaves differently to an end user than it did before. For example – adding a user changes the system behavior to allow that user to login in.
  • 系统状态显而易见的的改变。显而易见要求结束后的系统表现和发生前的不同。例如,添加一个用户以让其可以登陆。
  • A call to a 3rd party system. A 3rd party system is a dependency that we do not have control over in our test. If it touches the file system, or calls the network, or uses threads, or anything that makes our test slow, or inconsistent, it is a dependency we don’t have control over.
  • 一个对第三方系统的调用。第三方系统的依赖是测试中无法控制的。例如对文件系统,对网络,对线程或者任何使得测试变慢,不一致的不可控因素的依赖。

The third case (3rd parties) is where we end up using mock objects. In all other cases, we might have stubs to break dependencies, but our asserts will be against the system’s different states, or different return values.

第三种情况我们必须使用mock对象,在其他情况下,我们可以用stub对象解除依赖,但是我们的断言也会针对系统的不用状态或者不同的返回值。

你可能感兴趣的:(单元测试)