22/10/2017 - PHPUNIT
In this example we are going to setup up PHPUnit in a dummy application and run tests.
project
|-- src
|---- Application
|------ Service
|-------- TwitterService.php
|-- tests
|---- Application
|------ Service
|-------- TwitterServiceTest.php
|-- vendor
|---- ...
|-- composer.lock
|-- composer.json
|-- phpunit.xml
Run $ composer require phpunit/phpunit --dev
to install phpunit package.
Save file below as phpunit.xml
in project root.
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/5.1/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="vendor/autoload.php">
<testsuites>
<testsuite name="ApplicationSuite">
<directory>./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src</directory>
</whitelist>
</filter>
</phpunit>
Your test suite name is ApplicationSuite
and you need to place your test files under tests
folder in project root.
Assume that we have test class below.
namespace tests\Application\Service;
use PHPUnit\Framework\TestCase;
class TwitterServiceTest extends TestCase
{
public function testSetMessage()
{
}
public function testGetMessage()
{
}
}
Run all tests.
$ vendor/bin/phpunit
Run all tests by suite name.
$ vendor/bin/phpunit --configuration phpunit.xml --testsuite ApplicationSuite
Run all tests in a specific folder.
$ vendor/bin/phpunit tests/Application/Service
Run single test method in single test class. Note: If there is another test method name starts with testSetMessage
, PHPUnit would run it as well. e.g. testSetMessageAnother
$ vendor/bin/phpunit --filter testSetMessage TwitterServiceTest tests/Application/Service/TwitterServiceTest.php
Run all test methods in single test class.
$ vendor/bin/phpunit --filter TwitterServiceTest tests/Application/Service/TwitterServiceTest.php