TDD疑问

最近学习TDD开发,用在平时开发的时候,就会发现TDD并不完美,特别是测试先行和各种需要覆盖
的测试。存在疑问如下:

  • 是否真的需要一开始就写测试,然后一步一步驱动去开发呢;
  • 后续测试用例的维护,特别与关联其他部门的接口,各种mock和stub;
  • 耗费的时候比先写好代码再测试更大;

一些观点

对TDD有一些不成熟的想法,不一定非等需要严格按照TDD开发流程进行项目开发,找到适合自己的就行。TDD
对我来说很难掌握,但可以从TDD中学习和借鉴的是:

  • 开发自己列好测试清单,以便我们单元测试做得足够;
  • 重构自己写的代码;

后面在StackoverFlow上看到一个帖子How deep are your unit tests?,附上问题和比较喜欢的答案:

  1. 问题

The thing I’ve found about TDD is that its takes time to get your tests set up and being naturally lazy I always want to write as little code as possible. The first thing I seem do is test my constructor has set all the properties but is this overkill?

My question is to what level of granularity do you write you unit tests at?
…and is there a case of testing too much?

比较喜欢的两个回答:

  1. TDD创始人Kent Beck回答:

I get paid for code that works, not for tests, so my philosophy is to test as little as possible to reach a given level of confidence (I suspect this level of confidence is high compared to industry standards, but that could just be hubris). If I don’t typically make a kind of mistake (like setting the wrong variables in a constructor), I don’t test for it. I do tend to make sense of test errors, so I’m extra careful when I have logic with complicated conditionals. When coding on a team, I modify my strategy to carefully test code that we, collectively, tend to get wrong.

Different people will have different testing strategies based on this philosophy, but that seems reasonable to me given the immature state of understanding of how tests can best fit into the inner loop of coding. Ten or twenty years from now we’ll likely have a more universal theory of which tests to write, which tests not to write, and how to tell the difference. In the meantime, experimentation seems in order.

kitofr的回答

Everything should be made as simple as possible, but not simpler. - A. Einstein
One of the most misunderstood things about TDD is the first word in it. Test. That’s why BDD came along. Because people didn’t really understand that the first D was the important one, namely Driven. We all tend to think a little bit to much about the Testing, and a little bit to little about the driving of design. And I guess that this is a vague answer to your question, but you should probably consider how to drive your code, instead of what you actually are testing; that is something a Coverage-tool can help you with. Design is a quite bigger and more problematic issue.

后来看到耗子叔写了一篇TDD并不是看上去的那么美,比我写的好,思考的深。blush
另外关于Unit test VS TDD讨论也是十分精彩的,推荐阅读。