I am quite new to TDD and the first question which came into my mind is whether I should apply unit tests to every developed component. I am asking it since I observed that unit testing takes a开发者_开发问答 lot of time, especially when some changes into the requirements are provided. So, could you suggest something like best practices in TDD regarding unit testing?
A short description of TDD expressed in three rules:
- You are not allowed to write any production code unless it is to make a failing unit test pass.
- You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.
- You are not allowed to write any more production code than is sufficient to pass the one failing unit test.
And a longer description: http://jamesshore.com/Agile-Book/test_driven_development.html
And a more in-depth description: http://www.growing-object-oriented-software.com/
Just an observation - you said
I observed that unit testing takes a lot of time
which is true in the short view. But for code that's going to be around a while, the extra work saves time. I stressed the value of unit testing on one project I was on about years ago, telling everyone that would listen, "We don't have time to skip that step." And it's true. There are many places that time will be saved - testers will spend less time testing the app, kicking bugs back through whatever bug-tracking process you use, you'll spend less time remembering what you did weeks or months later so you can fix the bug, users will see fewer bugs, meaning they will spend less time yelling at you for broken apps. You'll spend less time on the phone at 2 AM hoping you can get the app fixed before the users come in the next day.
It all comes to to economics, in a way. For any code that's going in to production, trust me, you don't have time to skip that step. It'll cost you more time and your company more cash.
If the code's not going to prod, that is, it's a utility you wrote to help with some task, or see how the network layer really works, you want to adjust the amount of testing you do to suit the need. Experience will help guide you there to know the right amount.
TDD means that the tests drive the development of your components. You start by writing a unit test that specifies the behavior of the component, then you implement the component. So to answer your question:
should apply unit tests to every developed component
No, because the unit tests should already be written before developing the component.
The tests drive the development of your code. TDD is really all about defining the desired behaviour of your software, the fact that's it's all testable is just a good side effect.
A good essay on TDD is available here
精彩评论