Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Test-Driven Development with PHP 8
Test-Driven Development with PHP 8

Test-Driven Development with PHP 8: Build extensible, reliable, and maintainable enterprise-level applications using TDD and BDD with PHP

By Rainier Sarabia
€24.99 €16.99
Book Jan 2023 336 pages 1st Edition
eBook
€24.99 €16.99
Print
€30.99
Subscription
€14.99 Monthly
eBook
€24.99 €16.99
Print
€30.99
Subscription
€14.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Jan 13, 2023
Length 336 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781803230757
Category :
Languages :
Table of content icon View table of contents Preview book icon Preview Book

Test-Driven Development with PHP 8

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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn to organize and translate business requirements into maintainable software
  • Minimize regressions and bugs while releasing new features or bug fixes
  • Build maintainable applications using SOLID principles

Description

PHP web developers end up building complex enterprise projects without prior experience in test-driven and behavior-driven development which results in software that’s complex and difficult to maintain. This step-by-step guide helps you manage the complexities of large-scale web applications. It takes you through the processes of working on a project, starting from understanding business requirements and translating them into actual maintainable software, to automated deployments. You’ll learn how to break down business requirements into workable and actionable lists using Jira. Using those organized lists of business requirements, you’ll understand how to implement behavior-driven development (BDD) and test-driven development (TDD) to start writing maintainable PHP code. You’ll explore how to use the automated tests to help you stop introducing regressions to an application each time you release code by using continuous integration. By the end of this book, you’ll have learned how to start a PHP project, break down the requirements, build test scenarios and automated tests, and write more testable and maintainable PHP code. By learning these processes, you’ll be able to develop more maintainable, and reliable enterprise PHP applications.

What you will learn

Understand how to start a software project Discover how to use Jira as a tool to organize your tasks Explore when and how to write unit, integration, and functional tests using PHPUnit Write behavior-driven tests using Behat Apply SOLID principles to help you write more testable code Get the most out of your automated tests by using continuous integration Use continuous delivery to help you prepare your application for deployment

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Jan 13, 2023
Length 336 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781803230757
Category :
Languages :

Table of Contents

17 Chapters
Preface Chevron down icon Chevron up icon
Part 1 – Technical Background and Setup Chevron down icon Chevron up icon
Chapter 1: What Is Test-Driven Development and Why Use It in PHP? Chevron down icon Chevron up icon
Chapter 2: Understanding and Organizing the Business Requirements of Our Project Chevron down icon Chevron up icon
Chapter 3: Setting Up Our Development Environment Using Docker Containers Chevron down icon Chevron up icon
Chapter 4: Using Object-Oriented Programming in PHP Chevron down icon Chevron up icon
Part 2 – Implementing Test-Driven Development in a PHP Project Chevron down icon Chevron up icon
Chapter 5: Unit Testing Chevron down icon Chevron up icon
Chapter 6: Applying Behavior-Driven Development Chevron down icon Chevron up icon
Chapter 7: Building Solution Code with BDD and TDD Chevron down icon Chevron up icon
Chapter 8: Using TDD with SOLID Principles Chevron down icon Chevron up icon
Part 3 – Deployment Automation and Monitoring Chevron down icon Chevron up icon
Chapter 9: Continuous Integration Chevron down icon Chevron up icon
Chapter 10: Continuous Delivery Chevron down icon Chevron up icon
Chapter 11: Monitoring Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.