O'Reilly logo

Real-World Solutions for Developing High-Quality PHP Frameworks and Applications by Stefan Priebsch, Sebastian Bergmann

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 10. Testing Database Interaction

Michael Lively, Jr.

WHAT'S IN THIS CHAPTER?

  • Reasons not to write database tests

  • Reasons to write database tests

  • What to test

  • Mocking database connections

  • Using the PHPUnit database extension

  • Using database tests for regression testing

INTRODUCTION

In the application development process, we need to be certain that we are correctly working with our data. One of the best tools we have as developers to ensure that we are doing this is unit tests. Despite the usefulness of unit tests, my experience in reviewing code, writing code, and talking to other developers is that we tend to ignore the complete persistence of data when writing unit tests.

Although we test what we can with mock objects and stubs, we can sometimes completely ignore the actual code that stores the data into the database for later use. We can come up with a wealth of excuses for why we do this:

  • It makes tests take too long to run.

  • It is no longer testing a single unit; it is testing the database engine as well.

  • We assume the database works, so we do not need to test it.

  • Database testing is a pain in the neck, and those stupid fixtures take forever to write.

Those statements are true, but they do not take into account the entire picture. Sure, database tests may take a while, but would you rather an automated test suite take a few more minutes to write and a few seconds longer to run, and test a little more than the "experts" would like? Or, would you rather be blind-sided when you discover ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required