INTRODUCTION
When working under Agile we must develop based on tests. Test-driven programming is very useful for Agile because the development cycle is very short. All the developer must do is solve the next test.
The test-driven development lifecycle can be represented by the image below:
If you are programming with PHP I recommend the PHPUnit framework.
On Ubuntu it’s very simple to install PHPUnit:
$ sudo apt install phpunit
On other systems, the recommended approach will be using the composer or the pear repository. By the way, look at the PHPUnit documentation to have the best choice for your needs:
https://phpunit.de/documentation.html
TESTING A NEW CLASS
Our Scrum Master asked to begin a new project named Ferro, a CMS. We need to create a test that ensures we have a class named Ferro, supposed to be the main project’s class.
We will begin our new system, that will be a proof of concept CMS, creating our first test.
Our CMS will be named “Ferro”, so let’s create a new directory for our project with 2 folders:
$ mkdir Ferro;
$ mkdir Ferro/includes; mkdir Ferro/includes/classes
$ mkdir Ferro/tests; mkdir Ferro/tests/classes
Now, using your preferred text editor, create a file, FerroTest.php under the directory Ferro/tests/classes:
$ cd Ferro$ vim tests/classes/FerroTest.php
Write it in the file:
<?php
/**
* testing class Ferro
*/// include our class arquive for test
require ("includes/classes/Ferro.php");/**
* @covers Ferro
*/
final class FerroTest extends PHPUnit_Framework_TestCase
{
public function testNew()
{
$this->assertInstanceOf(
Ferro::class,
new Ferro
);
}
}?>
Now we will just create an empty file named Ferro.php so the PHP parser for the require command will not throw an error.
$ touch includes/classes/Ferro.php
We can test our inexistent class. It will result in an error also because the Ferro class still does not exists:
$ phpunit tests/classes/FerroTest.phpPHPUnit 5.1.3 by Sebastian Bergmann and contributors.E 1 / 1 (100%)Time: 33 ms, Memory: 4.00MbThere was 1 error:1) FerroTest::testNew
Error: Class 'Ferro' not found/home/filipo/Ferro/tests/classes/FerroTest.php:18FAILURES!
Tests: 1, Assertions: 0, Errors: 1.
Well, writing a trivial class on the empty file will fix it:
$ vi includes/classes/Ferro.php
and write so:
<?php
/**
* class Ferro
*/
class Ferro
{ } // end of Ferro
?>
Now the test will pass:
$ phpunit testes/classes/FerroTest.php
PHPUnit 5.1.3 by Sebastian Bergmann and contributors.. 1 / 1 (100%)Time: 70 ms, Memory: 4.00MbOK (1 test, 1 assertion)
It’s all! Our proof of concept CMS begun! Now we must wait for the Scrum Master tell us what the new functionalities our CMS must have. But it will be done in the next article.
Thank you!