What is TDD?
TDD is a simple way of developing software where we think about and define what needs to be the outcome of our programs before we start writing the actual codes that solve a problem.
TDD is a software development process where test cases are developed first before writing the actual code that solves a problem. The test cases will be written as PHP code that will use or call the solution code that developers will be building. The test case code that you build will trigger the development of the solution code that you will write to solve a problem.
From what I’ve seen, this literal description is what demotivates a lot of developers from applying this process. TDD is a process, and it’s a way of thinking. It’s not simply about writing unit tests.
The test program you write should always fail the first time you run it because you haven’t built the programs the test needs to pass yet. Then, you will basically have to build the solution codes that the test program will use until the test program itself gets the expected results from your solution codes. Literally, the failing test will drive you to write the codes to pass the test – hence the term TDD. Maybe you can even call it failing-TDD. It’s like saying “I wrote a test to fail my code, now I need to fix it.”
In TDD, I can see four main reasons why it’s important to write a failing test first. First, you will write a failing test and make sure your test framework application can recognize it. This ensures that your development environment is properly configured and you can run your test programs. Second, your failing test will help you define what solution or feature code you’d like to write, and what is expected for that test to pass. This will help you as a developer, in setting or focusing your mindset on the purpose of the feature code you are writing. Third, the failing tests you write will serve as reminders to know what other programs you need to complete. Fourth, writing your tests first will help ensure that your solution code is covered by automated tests.
By trying to make your solution code unit-testable, you are sometimes inadvertently making your codes less coupled – it’s like a cycle. As you continue to write loosely coupled codes, you will notice that your codes will start to look more organized and less of a tangled mess. As you continue writing solution code following the TDD process, it will continuously help you spot where tight couplings are in your product, sometimes encouraging you to refactor and decouple your code just to make it unit-testable. There are software development principles that will help you further improve your codes, such as the Single-Responsibility Principle, which will be discussed more in Chapter 8, Using TDD with SOLID Principles.
Now that we have defined and have a brief understanding of what TDD is, let’s go through some of the common misconceptions associated with it.