Automatic testing in PHP

testing means checking your program behave as expected by performing a battery of tests,runnable code-fragments that automatically test the correctness of parts (units) of the software.

well, testing is essential in software development. Testing makes your software more perfect. For php, we use PhpUnit for unit testing in php. But this in not the main point of todays article. In this article, I will show you how to design a automated testing in php.

Lets start with a simple program.
<?php
$fixture=array();
$fixture=’element’;
?>
in here, we took an array $fixture. Now the array index is 0, in the 2nd line, we gave an element ‘element’ in $fixture. Now the array index is 1.

now we are going to test the the element is successfully inserted or not.
Lets rewrite the program.
<?php
$fixture=array();
print count ($fixture)==0 ? “ok\n”:”not ok\n”;
$fixture=’element’;
print count ($fixture)==1 ? “ok\n”:”not ok\n”;
?>

now the output will show,
1.ok if the array is created
2.ok if the element is successfully inserted.

Now lets make it more automated by throwing an exception. Point to remember that this is the root of unit testing (php,java,any thing!) that throw an exception….

<?php
$fixture=array();
assertTrue(count ($fixture)==0);
$fixture = ‘element’;
assertTrue(count ($fixture)==1);

function assertTrue($condition)
{
if (!condition)
{
throw new Exception (‘Assertion failed’);
}
}
?>
The test is now completely automated. Instead of just testing as we did with our first version, with this version we have an automated test.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s