Book Image

PHPUnit Essentials

By : Zdenek Machek
Book Image

PHPUnit Essentials

By: Zdenek Machek

Overview of this book

<p>The ability to write unit tests and software testing have become skills that every PHP developer should master.<br /><br />This book is a practical guide to PHPUnit and unit testing, covering all aspects of writing PHPUnit tests and using them. The book shows why testable code is better code and how to write good tests with the help of simple and easy-to-understand examples.<br /><br />With this book, you will learn how to write, organize, and execute effective tests. Step-by-step techniques of how to write testable code, how to refactor the code, and how to run your tests are shown. You will also learn about advanced testing techniques, including how to test databases, APIs, and legacy code. PHPUnit Essentials is a guide for PHP developers who want to learn or improve their software testing skills. It is a book for developers who begin with testing but is also a good source of information for developers who are already familiar with PHPUnit.</p>
Table of Contents (21 chapters)
PHPUnit Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
5
Running Tests from the Command Line
Index

Test fixtures


When you are setting up a known state for tests, you have the following two options:

  • Set it before each test case class, runs once before and/or after each test case

  • Set it before each test method, runs before each test and/or after each test

Before and after each test method

The setUp() and tearDown() methods are the most common ones used to set a known state for tests and do clean up after the test is executed. By definition, it is called the fixture or test context—known state for tests.

The setUp() method is called before every test is executed. Each test method has set up know state and all required settings; you don't have to duplicate the same code for similar tests.

The tearDown() method is opposite to setUp(), and it is called when the test finishes. For example, when working with a file, it might be placed where fclose (closes an open file pointer) is required.

Note

There is one problem with the tearDown() method. If you have a bug in the code causing a fatal error, tearDown...