Briefly, a test is a code which runs and ensure that our code behaves as expected.
Here is an example of a test to check a mail validator function:
print ( validateEmail("test@site.com") && !validateEmail("test@site") && !validateEmail("@site") && ! validateEmail("with space@site.com") && !validateEmail("test@site.commm") && validateEmail("a-b_c@sub.site.com")) ? "function looks OK":"test fail";
Obliviously, we need more testing features (first of all to understand which test fails). So, let's use an existent tool to make and to run tests effectively and easily.
PHPUnit is a free powerful easy-to-use framework to manage PHP Unit tests.
- Installation: setup with pear (recommended) or download the source archive
- Test writing: include the main class, extend the PHPUnit_Framework_TestCase class and write inside one method for each unit test. Each method should call an existent superclass method, such as assertEquals($a, $b), assertTrue($a), etc... [online manual]
- Run: use a command line tool and type
phpunit fileWithTests.php
PHPunit will automatically run all the tests (=methods written in the class) and will show the detailed results of each one.
This is only a summary, consult the PHPunit official online manual to explore all the features.
One personal suggestion: write the tests BEFORE writing the code ! You will save time and write a better code.
No comments:
Post a Comment