1

What Is Test-Driven Development and Why Use It in PHP?

Developing web applications is fun and productive when using the PHP programming language. The learning curve to get started with PHP is relatively shallow, which is a very important trait of a programming language. There are a lot of open source learning materials, frameworks, packages, and full-blown extendable products backed by a very large open source community available for PHP developers. PHP is an enterprise-ready programming language and is widely used as a web-based solution to solve different business problems. Businesses and developers can quickly develop and deploy web applications with PHP. Once these businesses start to succeed and grow, they’ll need more features, bug fixes, and improvements to be released on top of the original solution. This is where it starts to get interesting. Maintenance of commercially successful software can be one of the biggest contributing factors to the cost of the software, especially when it’s not built to be easily maintainable or testable from the beginning. Implementing test-driven development (TDD) will improve the maintainability of the software and will help reduce the cost and time to market for a feature.

There’s a problem that most of us developers might have already experienced or observed: a feature or a bug fix has been released and it has caused more problems, regressions, or unintended software behavior. If you are coming from a development environment where most or all the quality assurance (QA) tests are done manually post-, pre-, or even mid-development, then you might have experienced the issues that I have mentioned. This is where implementing TDD can really help. TDD not only helps in implementing automated tests but also guides or even forces us in a way to develop cleaner and more loosely coupled codes. TDD helps developers write and build tests before even writing a single feature code – this helps ensure that whenever a feature or solution code is being written, there will be a corresponding test already written for it. It also helps us developers stop saying “I’ll add my unit tests later.”

Before writing any codes, it’s very important to understand what TDD is, and what it is not. There are some common misconceptions about TDD that we need to clear up to help us stay focused on what TDD really is. In this chapter, we will also try to use a very simple analogy and try to emphasize why we would want to implement TDD as a part of a software project.

In this chapter, we will be covering the following:

  • What is TDD?
  • Common misconceptions about TDD
  • Why should we even consider TDD?
  • What are we planning to achieve in this book?

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.

Common misconceptions about TDD

In this section, we’ll look at some of the misconceptions that I have personally observed that developers have about TDD. Time and time again, I’ve encountered people who have a poor understanding of TDD. When I talk to some of them about why they’re not a fan of TDD, they sometimes tell me reasons that are not even related to TDD.

Testing software is not my job as a developer; therefore, I don’t need TDD

I have said this myself. I used to think that I just needed to churn out solution code as fast as possible, test a little bit manually, and let the testing department ensure that everything is built correctly. This is probably the worst misconception I’ve ever had about TDD. As software developers, we develop software as solutions to problems. If we developers are the ones causing more problems, then we are not doing our jobs.

Developing with TDD is unnecessarily slow

I would be surprised if this were the first time you are hearing this. I first heard this from a client who had a technical background, not from a developer. I wasn’t a fan of TDD myself and willingly agreed with my client back then. Sure, it’s slower to write test codes and solution codes together; I would have to type more characters on my keyboard, after all!

When working on enterprise projects, from what I have experienced, TDD is what saved us from months of bugs and regressions. Writing tests and having good test coverage, which is discussed in Chapter 5, Unit Testing, will help ensure that the next time someone else touches the code or adds new features, no regressions will be introduced. TDD will help you build a lot of automated tests, and running these tests is cheaper and quicker than handing over your untested solution code to a testing team or testing company for manual testing.

Writing automated or unit tests is TDD

TDD is not about writing automated tests or unit tests for existing functionalities. TDD is not about getting your QA department or getting a third-party company to write automated tests for existing software. This is the exact opposite of TDD.

The most common misconception I have observed is that some developers and testers assume that TDD has something to do with testers writing automated tests for the codes that the developers build. I believe that this is a very bad misconception. It’s no different from developing a program and sending it to the QA department for manual testing.

Getting testers to write automated functional tests is a very good thing, especially for existing functionalities that do not have automated tests, but this should only be thought of as supplementary test coverage for software and not be confused with TDD.

TDD is a silver bullet

The last misconception that I have encountered is assuming that if we developers have built excellent test coverage by following TDD, we will no longer need input from the software development department and QA department or team. Time and time again, I’ve proven myself wrong, believing that code that’s written via the TDD methodology is bulletproof. I am very fortunate to work with knowledgeable and skilled software engineers and test engineers. Code reviews are critical; always get your codes and test scenarios peer-reviewed. Edge-case tests and functional scenarios that the developers might have overlooked will cause problems – and in my experience, they have caused big problems.

It is very important for the development and testing teams to properly understand the functional and acceptance test cases so that all imaginable scenarios are covered: the different types of tests will be covered in Chapter 5, Unit Testing. This is where behavioral-driven development (BDD) will start to make sense; BDD will be discussed in more detail in Chapter 6, Applying Behaviour-Driven Development. I have worked with test engineers and QA personnel who can come up with edge cases that I couldn’t have imagined.

We have gone through some common misconceptions I have encountered about TDD. Now let’s try to make a case for why we’d want to consider using TDD in our development process.

Why should we even consider TDD?

Why would I want my codes to be driven by tests? I want my codes to be driven by requirements and happy clients! You may have heard about the term TDD and felt uncomfortable with it. When I first heard about the term TDD, I was a bit uncomfortable with it too. Why would you want to waste time writing test code to test solution code that doesn’t exist yet? Seriously, I need to write the actual code that solves the business problem, and you want me to write tests first? As a matter of fact, some developers I have trained and worked with have had this same question too – and it’s the exact same question that was stopping them from getting interested in TDD!

When I started my software development career, I was working for a small company where we were required to deliver results as soon as possible, in very few iterations. Just thinking about writing automated tests for my super-quickly written codes was a big waste of time! Therefore, when I read about TDD for the first time, I was not interested. I ignored my meatball spaghetti codes; all I cared about was making sure that the client got the intended business results in the shortest amount of time. Solving the regressions that would be caused by the bad codes as a problem for later. I needed to make the client happy as soon as possible – that is, right now. This is probably one of the most short-sighted mistakes I made in my professional career. Most of the time, my colleagues and I had to add features and maintain our own bowl of spaghetti mess. Time and time again, we would hate our past selves when we saw the mess we had made. Early in our careers as software developers, we have a lot of mistakes, inefficiencies, and short-sightedness. Thankfully, we are not the first ones to encounter these problems. There are processes that we can follow to help us improve the quality of the software we produce, and one of them is TDD.

Now, after making so many mistakes, so many failures, and after working on hundreds of business-critical software projects, I can’t even imagine living a day without writing tests by following TDD. When working on a project, I don’t think I can even sleep properly at night without knowing whether my automated tests have passed or failed; at least I have the tests!

Imagine creating a clean my home to-do list on your phone: you only have one item on it and it’s clean the coffee machine. You write that item down, get distracted and forget about it, and go on with your day. When you check your list again, you will realize that you have not cleaned the coffee machine yet! You then go ahead and clean the machine, and mark the item as completed.

Well, that’s a bit like how TDD works. You write a failing test, then you write the codes to pass the test – and with the to-do list, you write out “clean the coffee machine”; then after you clean the actual coffee machine, you cross it out from your list.

Important note

Before anything else, I mean right now, you need to understand that it is very normal for a test to fail in the beginning and you need to be very comfortable with it and accept it. It’s like writing the coffee machine checklist item on your phone. Once you add that to your to-do list, the to-do list is failing you until you pass it by marking the to-do item as complete. You need to write the failing test first before writing any program to pass that test. This is a part of the Red, Green, Refactor (RGR) concept, which will be discussed further in Chapter 7, Building Solution Code with BDD and TDD.

Going back to your phone, you add more items to that list: clean the kitchen, clean the bedroom, clean the bathroom… You then go to the gym and get distracted. You remember your list and want to know whether you have actually cleaned your home before going out, so you view your to-do list. You realize you only completed one item on the list; you will have to go back and finish the other tasks to fully satisfy the clean my home to-do list. When you return home, you can continue cleaning your home and ticking off your to-do list:

Figure 1.1 – Incomplete to-do list

Figure 1.1 – Incomplete to-do list

You can think of the incomplete items on your to-do list as failing tests. The action of cleaning something is writing the codes to satisfy the failing to-do list item. You, finishing the task of cleaning the bedroom or bathroom, is akin to passing a test. Now imagine you have completed all the cleanings and so on, and you’ve marked all the items as checked on your clean my home list on your phone: you’re done!

Figure 1.2 – Completed to-do list

Figure 1.2 – Completed to-do list

Now you can imagine your clean my home list as a test as well. Your test is satisfied by the overall completeness of the codes that were built to satisfy your smaller unit and integration tests (the types of tests will be discussed in detail in Chapter 7, Building Solution Code with BDD and TDD).

We can consider the clean my home list as a test. This test runs through all the processes of cleaning a home. Some objects inside it involve cleaning the bathroom, some the kitchen, and so on. Just as we did when writing the to-do list, you write the failing test that represents the bigger picture first and not the smaller, more detailed tests:

// Test Method
public function testCanCleanMyHome()
{
     $isMyHomeClean = $this->getCleaner()->clean();
     $this->assertTrue($isMyHomeClean);
}

After writing the failing clean my home test, which can only be satisfied by building the programs to clean each part of the house, we can start writing the failing tests for the smaller parts of the solution:

// Test Method
public function testCanCleanCoffeeMachine()
{
     $isMyCoffeeMachineClean = $this->getCleaner()->
         clean();
     $this->assertTrue($isMyCoffeeMachineClean);
}

Now imagine after cleaning your home, you ended up making a mess of the bedroom and you have unchecked the clean my bedroom item on your list. Technically speaking, your clean my home to-do list is now incomplete again. The same thing happens when after you have passed all the tests and someone in your team or you modifies the code and changes the expected behavior. If you then run your testCanCleanMyHome() test, it will fail. If we then run these automated tests before we deploy our codes to production, we will be able to catch regressions early on! It will be easier to catch code changes that break expected behaviors!

This is an oversimplification, but you will realize as we go along that this is what TDD is like. It’s not a bad, time-wasting exercise after all!

We are humans and we tend to make mistakes – at least that’s what I believe. Although if you think you don’t make mistakes, you might as well just pry the Delete key out of your keyboard as you don’t need it. I’ve made so many mistakes, and to help build confidence in my code, I ensure to pass all the tests and get the code peer-reviewed.

Implementing TDD and having a lot of test coverage for your software is a great way of helping you and your team spot mistakes before they cause harm in production. Having all these different types of tests running before deployment helps me sleep better at night.

What are we planning to achieve in this book?

Well, obviously, we want to get a better understanding of TDD – not just with theories but with actual usable and applicable understanding. We want to help ourselves write better codes that will benefit other developers who will work on your own codes as well. We want to be able to lay a foundation for how to write software that will be robust and sturdy, self-diagnosing, and more extensible.

We used a very simple analogy earlier using the clean my home to-do list to try to explain what TDD is and how it is done – but this will not be very exciting if it’s all just theory. In this book, we will try to implement TDD for real using an example project!

We will be building an example project that will help us do the following:

  • Identify what a client or a business wants to achieve
  • Translate those requirements into actual tickets
  • Learn how to implement TDD and BDD
  • Write clean codes following design patterns and best practices
  • Automatically run all tests using continuous integration
  • Automatically deploy our codes using continuous deployment

Summary

In this chapter, we have defined what TDD is and what it is not. We tried to relate TDD to simple everyday tasks such as cleaning certain parts of your home. By trying to clear up common misconceptions about TDD, hopefully, we will have a clearer understanding of what TDD is. TDD is a process; it’s not solely about writing unit tests and automated tests.

We also covered why we would want to use TDD when developing PHP applications. TDD helps us develop cleaner, decoupled, maintainable codes, and it helps us be more confident that we won’t introduce regressions whenever we release codes, thanks to the automated test coverage that is inherently built by following TDD.

In the next chapter, we will start building the example project by coming up with a simple hypothetical business challenge first and making sense of what needs to be built to solve the problem.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.64.132