How to get started Unit testing with PHPUnit ( basic stand alone example no frameworks )
Very Basic Example Test with PHPUnit
In this very quick tutorial, we will write our first unit test.
Step #1
Let’s create Basic-Example-Test-PHPUnit/composer.json
In this composer file add the following:
{
"require-dev": {
"phpunit/phpunit": "^9"
},
"autoload": {
"psr-4": {
"SimpleTest\\":"src"
}
},
"config": {
"optimize-autoloader": true
}
}
Step #2
We will create a tiny class in Basic-Example-Test-PHPUnit/src/Hello.php
The name of the directory “Basic-Example-Test-PHPUnit” is up to you, now in our class Hello we will simply say Hello to some $name variable.
namespace SimpleTest;
/**
*
*/
class Hello
{
private $name;
function __construct( $name )
{
$this->name = $name;
}
public function say_hello(){
return 'Hello ' . $this->name;
}
}
Step #3
Awesome now let’s run composer install to bring in our dependencies.
$ composer install
Step #4
We can now write our test, create the test in Basic-Example-Test-PHPUnit/tests/HelloTest.php
in HelloTest add the following:
use PHPUnit\Framework\TestCase;
use SimpleTest\Hello;
/**
*
*/
class HelloTest extends TestCase
{
public function testSayHello(): void
{
$hello = new Hello( 'World' );
$this->assertEquals(
'Hello World',
$hello->say_hello()
);
}
}
Read more about PHPUnit here: https://phpunit.de/getting-started/phpunit-9.html.
Try working example code on GitHub
clone this
git clone https://github.com/devuri/Basic-Example-Test-PHPUnit.git
Installer
composer install
Run the Tests
Execute all tests declared in *Test.php sourcecode files in the tests directory.
./vendor/bin/phpunit tests
Output.
PHPUnit 9.5.0 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 00:00.004, Memory: 4.00 MB
OK (1 tests, 1 assertions)