If you are aware of agile development methods, you have probably heard about test driven development. As I began to play more and more with symfony's unit testing tool (known as lime), I asked
mysefl how to set up a test driven development (TDD).
In fact, I do not beleive in writing test before code. It is not easy to test a method that doesn't exist, especially if the class does not exist either. So begining with writing the test before a
single line of code appeared to me like a masochist plan. To me it sounds we have several phases in writing code :
1 - write code until something work
2 - refactor the code to the right layer
3 - write the complete specifications of this code with tests.
4 - complete your code until all tests pass
I do think the first part is the creative part of the developer's work. The less you set structural constraints the better and the quicker it is. This part normally finish with a working prototype
of code. The danger would be to let this as is and go in production with it.
The second part supposes the developers have a good understanding of the framework decoupled MVC structure and know the right place for everything. It can happen you work with a developper who can
do these two steps in the same move, this is often the signature of well experienced developers.
The rest of this article will explain my experience of the two last steps.
So when I code, the first thing I do is to code until I had something working. Then I refactore little pieces of generic code in external classes that I placed in the lib directory of my plugin /
project. This simply makes the code more easy to test.
When I began to write unit tests for my functions, I realized I could take advantage of this moment to also define how I exactly want this functions to behave!
So I tested these functions for things it wasn't doing yet, deciding when I was expecting it to send exceptions and handling different limit use cases. The whole process took me 10 minutes. In 10
minutes I exactly knew how I wanted it to interact with the rest of the code and in the same time, I also ensured I will have no regressions on that parts because it s all what tests are about
.
As expected, most of the tests didn't pass at first. Then I began to implement the rest of functionnalities. I was a bit surprised to notice I couldn't reach the 100% tests because sometimes PHP
does not behave the way you think, by example getElementsByTagName method strangely do send any exception when you ask for a tag that doesn't exist nor when you feed it whith a non XML document. In
this case, I could spot the limitations of my code and document them as long as there was nothing I could do to make this better.