///SimpleTest: Unit Testing for PHP

SimpleTest: Unit Testing for PHP

We recently looked at front-end testing of web applications with Selenium. Today, we’ll take another approach to testing your PHP applications: backend unit testing for your actual PHP code. As part of our posts on test driven development, here’s a quick intro to using SimpleTest to test your PHP applications.

SimpleTest is a PHP unit testing and web testing framework along the lines of JUnit and JWebUnit. It provides a comprehensive set of APIs for testing everything from your class methods to your SSL-secured authentication pages.

Unit testing in PHP generally validates that individual sections of your source code are functioning as expected. As your project grows, it’s hard to remember what each and every module is responsible for, especially with multiple developers. Unit tests help check that a function or method does what it’s meant to, and when run during a build process or around version control commits, can check that recent changes haven’t broken expected functionality.

Let’s look at a simple SimpleTest example:

UnitTestCase('Test of Arithmetic');
    }

    function testAddition() {
        $arithmetic = new Arithmetic();
        $result = $arithmetic->add(1,1);
        $this->assertEqual($result, 2);
    }
}
?>

SimpleTest provides PHP classes that serve as the ground work for unit testing. When we define a new unit test case – in this case, “TestOfArithmetic”, SimpleTest automatically works out what tests you’ve defined in order to run them. We then simple create new methods for our tests, run whatever logic we need, and use assert calls to check that we have achieved our expected outcome. In this case, we want to assert that the return value of Arithmetic::add(1, 1) equals 2.

This may seem rather lengthy for a single test, but additional tests can be added on in as little as a single line of code, and an entire application can be quickly checked for reliability with just a few hundred lines of unit tests. Once this is in place, we can run our unit tests by loading up this script in our browser, and if everything is in order, we see a nice and concise status page displaying the results of the tests.

Of course, why write tests after you write your application code, when you could write it sooner and sooner, and maybe even before? That’s the approach of test driven development (TDD) – SimpleTest is perfectly happy with writing tests for code that doesn’t exist yet. TDD, from one of the guys who created Extreme Programming (XP), basically involves writing tests to define the design of code, and then working away at the code till it passes the tests, and SimpleTest is a great way to achieve it in PHP.

SimpleTest is hosted on SourceForge, so head over and try it out. They’ve also got a great tutorial on their main project site.

2010-05-19T21:52:49+00:00 July 14th, 2008|PHP|0 Comments

About the Author:

Leave A Comment