Saturday, May 7, 2011

Test Driven Development with PHP

Long time I was trying to explore if there is good unit test framework in PHP and recently got opportunity to work on for one of my projects. Its Simple Test PHP Unit Test Framework.

It has support for SSL, forms, frames, proxies and basic authentication. What makes Simple Test Framework immediately useful to the PHP developer is the internal web browser. This allows tests that navigate web sites, fill in forms and test pages. Being able to write these test in PHP means that it is easy to write integrated tests. An example might be confirming that a user was written to a database after a signing up through the web site.

There are basically two types of Test Case:

1. Unit Test Cases
a. The UnitTestCase class will typically generate test events when run and these events are sent to an observing reporter using methods inherited from UnitTestCase.
b. Autorun.php file does the expected work of pulling in the definitions of UnitTestCase. It collects all test classes in the current file and runs them automagically. It does this by setting up an exit handler.

Code Snippet:


Some of the Base Functions and their description:
- assertTrue($x) Fail unless $x evaluates true
- assertFalse($x) Fail unless $x evaluates false

2. Web Test Case

a. The WebTestCase includes facilities for navigation, content and cookie checks and form handling. Usage of these test cases is similar to the UnitTestCase.
b. Inorder to run test cases as part of a group, in this scenarion we use group testing. The test cases should really be placed in files without the runner code.
c. The setUp() method is run just before each and every test method.
d. The tearDown() is run just after each and every test method.
e. The name of the test case function is always prefixed by the word test. eg. if the test case is checklogin then you will require to
define the function as testchecklogin.
Code Snippet:
# For checking the response code of a URL
File: lastcraft_test.php


File: runlastcraft_test.php


# For checking the login functionallity


Some of the Base Functions and their description:
- getUrl() => The current location
- setMaximumRedirects($max) => Stop after this many redirects
- assertResponse($codes) => Pass if HTTP response matches this list
- assertField($name, $value) => Pass if an input tag with this name has this value
- setField($name, $value) => Sets the input tag with this name with this value
- clickSubmit($label) => Click the first button with this label
- assertText($name) => Pass if matches visible and "alt" text
- assertTitle($title) => Pass if title is an exact match

One can explore more on Simple Test PHP Unit Testing Framework Its pretty clean mechnism to follow your TDD

No comments: