[PHP] PHPUnit Installation, Configuration, and Examples

PHPUnit Installation and Sample Test

  1. Many people online recommend installing via PEAR. I tried various methods from different blog posts, but all failed.
  2. The method that worked for me is more straightforward:

Download link:

https://phpunit.de/index.html

The download is a .phar PHP extension. Download the PHPUnit version that matches your PHP version.

image001

Follow the instructions at https://phpunit.de/manual/current/en/installation.html#installation.phar.windows step by step.

  1. Download PHPUnit.phar to a folder, for example: C:\bin\
  2. Add this folder C:\bin\ to the Path environment variable
  3. In the command line, navigate to C:\bin and enter:
  4. echo @php "%~dpophpunit.phar"%*>phpunit.cmd

In any command line location, enter:

1
phpunit --version

You should see:

image003

At this point, PHPUnit is successfully installed.

Test Example:

SayHello.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php

class SayHello
{
    public function printHello()
    {
        echo 'Hello';
        return 'Hello';
    }
}
?>

TestSayHello.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?php

require_once 'SayHello.php';

class TestSayHello extends PHPUnit_Framework_TestCase
{
    public function setUp() { }

    public function tearDown() { }

    public function testConnectionIsValid()
    {
        $hi = new SayHello();
        $this->assertTrue($hi->printHello() == 'Hello');
    }
}
?>

The SayHello class prints “Hello” to the screen and returns “Hello”.

TestSayHello verifies whether the SayHello class correctly returns the “Hello” string.

Run it in the command line, and the test passes.

image005

Configuring PHPUnit in PHPStorm

Older versions of PHPStorm may not support PHPUnit well and will throw:

Warning: require_once(PHPUnit/Runner/Version.php)

See:

http://stackoverflow.com/questions/30278588/phpstorm-via-phpunit-phar-warning-require-oncephpunit-runner-version-php

This article uses PHPStorm 10. Download link:

https://www.jetbrains.com/phpstorm/?fromMenu

  1. Open the two files from earlier

image007

  1. Open Settings: File => Settings

Configure PHP version:

image009

Configure PHPUnit

image011

Sample Test

Select TestSayHello and run it directly. The result:

image013