一直觉得,近年来,真正有意义的技术或者思想只有两个:Refactor(重构)和TDD(Test Driven Development,测试驱动开发)。有趣的是,这两个都是从SmallTalk流传出来的。

单元测试的重要性自不必提。今天和大家分享一下在学习TDD中感受到的几点心得。

1、先写测试,后实现代码

We are thinking about how the class and its methods are used instead of how to implement it, 
which 
is an important distinction. This is why many people refer to test-driven development as
 
much a design technique 
as a testing technique.

2、只实现当前测试中所需的最小功能的代码,尽管有时并不符合逻辑

There is a balance to archieve between anticipating futher tests and implementation and being 
totally ignorant of the next text. In the beginning, you should focus on the test. You
'
re writing and 
not thinking about the other tests. As you become familiar with the technique and the task, you 
can increase the size of the steps. You should always keep in mind that larger steps and harder 
to debug than smaller steps.

3、测试代码中尽量避免冗余

Before we decide with test to implement next, we need to make sure that there is no code 
duplication. Use 
private instant variable and Use SetUp &
 TearDown Property. Notice to move     
duplication variables.

4、随着测试的深入,不得不逐渐的修改代码,甚至是对结构的大规模修改。与此同时。代码本身也逐渐靠近实际的逻辑要求。但是,任何时候都不需要也不应该修改先前的测试代码,并且应该保证其的成功运行。

You should notice that we made big changes to the entire implementation, and no tests were 
broken afterward. This 
is a good example of building confidence in
 the code that we have test 
for.We are assured that, base on our tests, the code is no worse that is previously.

5、延迟实现   Delaying Implementatin Decisions

We did not do this because we are trying to let the tests drive the need for functionality instead 
of us thinking we know what 
is needed and then writing tests that verify than thinking. It is
 a 
difference that 
this test demonstrats very clearly.

其实,TDD的关键在于RD自身出发点的转换。一般情况下,我们习惯于考虑如何实现功能,用什么样的数据结构、用什么算法、怎样分层、怎样传递值、……而在作TDD的时候,我们必须转换为只注重功能的本身而不是实现的方法或细节。或许有些难以理解,特别是面对不合逻辑的实现代码时。其实,正如前文所说,如果把TDD看作是一种设计技术而不是测试技术,也许我们会很好的理解这些。

有一种说法叫做“不能让RD测试自己的代码”。这样说的原因是RD只关注与程序的结构和实现,不能从功能的角度从外界考虑程序的流程。也许,只有置身事外,才能做好TDD的测试和开发。
posted on 2004-08-03 16:19  香依香偎孤旅独行的驿站  阅读(908)  评论(1编辑  收藏  举报