当你没有提到在哪种语言环境中,你的代码...
正如我在Smalltalk工作,语法检查在编辑器中,而I型,每当我接受的方法,所以那不是问题。 (对于那些不知道Smalltalk的人来说:它不是基于文件的,而是面向对象的;这意味着你一次一个地向类对象添加方法对象,并且系统会按照原样编译“接受“编辑)。
对于小算法或者不需要大框架/设置的小方法,我添加一点评论来测试该方法,并且可以通过点击来执行。还有一个测试运行者提取所有这些并将其作为单元测试运行。 对于更大的内容,每隔几个方法就会更新一个TestCase类,并随时点击测试运行器按钮,从而阻止我进入红灯。
所以我会说,测试每10行左右完成一次。我承认,这样做需要一个高度反应和增量的IDE - 否则,它不能这么容易完成,我会在测试之前回复说一个大致的字母大小的页面代码。我不认为可编译性是“测试”,因此语法正确性不计算在内。
编辑:为了您的娱乐,这里是从集合类一个具体的例子:
对于那些谁也不知道Smalltalk中:
引号字符串评论;
+/-是创建测量值的操作员;
/创建分数;
{...}是数组创建;
最后的测试用例可以在编辑器中直接执行(所谓的doIt)。
sum
"sum up all elements.
This is implemented using a variant of the normal inject:into: pattern.
The reason for this is that it is not known whether we are dealing with number
(i.e. if 0 is a good initial value for the sum).
Consider a collection of measurement or physical objects, 0 would be the unitless
value and would not be appropriate to add with the unit-ed objects."
| sum sample |
sample := self anElement.
sum := self inject: sample into: [:accum :each | accum + each].
^sum - sample.
"
TestCase should: [ { } sum ] raise:Error.
TestCase should: [ '' sum ] raise:Error.
TestCase assert: ({ 1 } sum = 1).
TestCase assert: ({ 1. 2. 3. 4. } sum = 10).
TestCase assert: ((1 to:10) sum = 55).
TestCase assert: ('abc' asByteArray sum = 294).
TestCase assert: ({ 10 +/- 2.
20 +/- 4.
100 +/- 10 } sum = (130 +/- 16)).
TestCase assert: ({ (1/9).
(1/7).
} sum = (16/63)).
"
为什么?纯语义。关键是决定代码应该先做些什么。无论你是正确的测试验证所需的行为或代码,以获得所需的行为第一次真的没有什么区别。 – 2009-01-16 12:18:37
首先编写测试有助于设计,因为它会迫使您针对您正在构建的API编写代码。它可以完全改变你实现面向公众的API的方式。 – 2009-01-16 12:53:55