單元測試的基本觀念

Source: The art of unit testing with examples in .NET, Roy Osherove
http://www.amazon.com/Art-Unit-Testing-Examples-Net/dp/1933988274/ref=sr_1_1?ie=UTF8&s=books&qid=1267086529&sr=1-1
Chapter 1 The basics of unit testing

1. Unit test的定義
為了讓大家有相同的認知, 作者定義了unit test是什麼.
(1) A unit test is a piece of a code (usually a method) that invokes another piece of code and checks the correctness of some assumptions afterward
(2) 如果assumption證明是錯的話, 這個unit test就算失敗.
(3) 一個unit是一個method 或是function (這一點是大家容易誤解或是忘記的)

一般人會怎麼做unit teest呢? 通常有以下幾類:
(1) 寫個console, 來呼叫你所寫的程式, 去確認你程式的正確性
(2) 寫個有UI的程式, 可能是GUI或是網頁的程式, 然後上面可能會有些button, 然後藉由按這些button來測試你的程式對不對

2. 什麼是好的unit test
通常大家都是知道要做unit test, 可是什麼樣的unit test才是一個好的unit test呢? 作者列出一些特性
(1) It should be automated and repeatable
(2) It hsould be easy to implement
(3) Once it's written, it should remain for future use
(4) Anyone should be able to run it
(5) It should run at the push of a button
(6) It should run quickly

個人覺得對大多數的人來說(2), (3), (6)不容易做到, 因為通常跑下來都要很久, 並且要不少時間去implement.

這時候作者問了一些問題:
- Can I run and get results from a unit test I wrote two weeks or months or years ago?
- Can any member of my team run and get results from a unit test I wrote two weeks months ago?
- Can I run all the unit tests I have written in no more than a few minutes?
- Can I run all the unit tests I have written at the push of a butoon?
- Can I write a basica unit test in no more than a few minutes?

如果這些問題其中有一個回答是"No"的話, 作者認為你可能不是在做 unit test, 而是在做integration test. 大家一定覺得很好奇, 真的以前都想錯了嗎? 讓我們來看看作者對integration test的定義.

3. Integration Test的定義
Integration testing means testing two or more dependent software modules as a group

也就是說
An integration test exercises many units of code that work together to evaluate or more expected results from the software.
A unit test usually exercises and tests only a single unit in isolation. (要注意single和isolation這兩個重點)

4. Good unit test的定義
所以最後作者做個總結, 定義什麼才是good unit test.
(1) A unit test is an automated piece of code that invokes the method or class being tested and then check some assumptions about the logical behavior of that method or class.
(2) A unit test is almost always written using a unit-testing framework
(3) It can be written easily and runs quickly
(4) It's fully automated, trustworthly, readable, and maintainable.


arrow
arrow
    全站熱搜

    kojenchieh 發表在 痞客邦 留言(2) 人氣()