1. Installing PHPUnit
Requirements
PHP Archive (PHAR)
Windows
Verifying PHPUnit PHAR Releases
Composer
Optional packages
2. Writing Tests for PHPUnit
Test Dependencies
Data Providers
Testing Exceptions
Testing PHP Errors
Testing Output
Error output
Edge cases
3. The Command-Line Test Runner
Command-Line Options
4. Fixtures
More setUp() than tearDown()
Variations
Sharing Fixture
Global State
5. Organizing Tests
Composing a Test Suite Using the Filesystem
Composing a Test Suite Using XML Configuration
6. Risky Tests
Useless Tests
Unintentionally Covered Code
Output During Test Execution
Test Execution Timeout
Global State Manipulation
7. Incomplete and Skipped Tests
Incomplete Tests
Skipping Tests
Skipping Tests using @requires
8. Database Testing
Supported Vendors for Database Testing
Difficulties in Database Testing
The four stages of a database test
1. Clean-Up Database
2. Set up fixture
3–5. Run Test, Verify outcome and Teardown
Configuration of a PHPUnit Database TestCase
Implementing getConnection()
Implementing getDataSet()
What about the Database Schema (DDL)?
Tip: Use your own Abstract Database TestCase
Understanding DataSets and DataTables
Available Implementations
Beware of Foreign Keys
Implementing your own DataSets/DataTables
The Connection API
Database Assertions API
Asserting the Row-Count of a Table
Asserting the State of a Table
Asserting the Result of a Query
Asserting the State of Multiple Tables
Frequently Asked Questions
Will PHPUnit (re-)create the database schema for each test?
Am I required to use PDO in my application for the Database Extension to work?
What can I do, when I get a Too much Connections Error?
How to handle NULL with Flat XML / CSV Datasets?
9. Test Doubles
Stubs
Mock Objects
Prophecy
Mocking Traits and Abstract Classes
Stubbing and Mocking Web Services
Mocking the Filesystem
10. Testing Practices
During Development
During Debugging
11. Code Coverage Analysis
Software Metrics for Code Coverage
Whitelisting Files
Ignoring Code Blocks
Specifying Covered Methods
Edge Cases
12. Other Uses for Tests
Agile Documentation
Cross-Team Tests
13. Logging
Test Results (XML)
Test Results (TAP)
Test Results (JSON)
Code Coverage (XML)
Code Coverage (TEXT)
14. Extending PHPUnit
Subclass PHPUnit_Framework_TestCase
Write custom assertions
Implement PHPUnit_Framework_TestListener
Subclass PHPUnit_Extensions_TestDecorator
Implement PHPUnit_Framework_Test
A. Assertions
assertArrayHasKey()
assertClassHasAttribute()
assertArraySubset()
assertClassHasStaticAttribute()
assertContains()
assertContainsOnly()
assertContainsOnlyInstancesOf()
assertCount()
assertEmpty()
assertEqualXMLStructure()
assertEquals()
assertFalse()
assertFileEquals()
assertFileExists()
assertGreaterThan()
assertGreaterThanOrEqual()
assertInfinite()
assertInstanceOf()
assertInternalType()
assertJsonFileEqualsJsonFile()
assertJsonStringEqualsJsonFile()
assertJsonStringEqualsJsonString()
assertLessThan()
assertLessThanOrEqual()
assertNan()
assertNull()
assertObjectHasAttribute()
assertRegExp()
assertStringMatchesFormat()
assertStringMatchesFormatFile()
assertSame()
assertStringEndsWith()
assertStringEqualsFile()
assertStringStartsWith()
assertThat()
assertTrue()
assertXmlFileEqualsXmlFile()
assertXmlStringEqualsXmlFile()
assertXmlStringEqualsXmlString()
B. Annotations
@author
@after
@afterClass
@backupGlobals
@backupStaticAttributes
@before
@beforeClass
@codeCoverageIgnore*
@covers
@coversDefaultClass
@coversNothing
@dataProvider
@depends
@expectedException
@expectedExceptionCode
@expectedExceptionMessage
@expectedExceptionMessageRegExp
@group
@large
@medium
@preserveGlobalState
@requires
@runTestsInSeparateProcesses
@runInSeparateProcess
@small
@test
@testdox
@ticket
@uses
C. The XML Configuration File
PHPUnit
Test Suites
Groups
Whitelisting Files for Code Coverage
Logging
Test Listeners
Setting PHP INI settings, Constants and Global Variables
Configuring Browsers for Selenium RC
D. Index
E. Bibliography
F. Copyright


Appendix C. The XML Configuration File

PHPUnit

The attributes of the <phpunit> element can be used to configure PHPUnit's core functionality.

<phpunit
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/5.2/phpunit.xsd"
         backupGlobals="true"
         backupStaticAttributes="false"
         <!--bootstrap="/path/to/bootstrap.php"-->
         cacheTokens="false"
         colors="false"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         forceCoversAnnotation="false"
         mapTestClassNameToCoveredClassName="false"
         printerClass="PHPUnit_TextUI_ResultPrinter"
         <!--printerFile="/path/to/ResultPrinter.php"-->
         processIsolation="false"
         stopOnError="false"
         stopOnFailure="false"
         stopOnIncomplete="false"
         stopOnSkipped="false"
         stopOnRisky="false"
         testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader"
         <!--testSuiteLoaderFile="/path/to/StandardTestSuiteLoader.php"-->
         timeoutForSmallTests="1"
         timeoutForMediumTests="10"
         timeoutForLargeTests="60"
         verbose="false">
  <!-- ... -->
</phpunit>

The XML configuration above corresponds to the default behaviour of the TextUI test runner documented in the section called “Command-Line Options”.

Additional options that are not available as command-line options are:

convertErrorsToExceptions

By default, PHPUnit will install an error handler that converts the following errors to exceptions:

  • E_WARNING
  • E_NOTICE
  • E_USER_ERROR
  • E_USER_WARNING
  • E_USER_NOTICE
  • E_STRICT
  • E_RECOVERABLE_ERROR
  • E_DEPRECATED
  • E_USER_DEPRECATED

Set convertErrorsToExceptions to false to disable this feature.

convertNoticesToExceptions

When set to false, the error handler installed by convertErrorsToExceptions will not convert E_NOTICE, E_USER_NOTICE, or E_STRICT errors to exceptions.

convertWarningsToExceptions

When set to false, the error handler installed by convertErrorsToExceptions will not convert E_WARNING or E_USER_WARNING errors to exceptions.

forceCoversAnnotation

Code Coverage will only be recorded for tests that use the @covers annotation documented in the section called “@covers”.

timeoutForLargeTests

If time limits based on test size are enforced then this attribute sets the timeout for all tests marked as @large. If a test does not complete within its configured timeout, it will fail.

timeoutForMediumTests

If time limits based on test size are enforced then this attribute sets the timeout for all tests marked as @medium. If a test does not complete within its configured timeout, it will fail.

timeoutForSmallTests

If time limits based on test size are enforced then this attribute sets the timeout for all tests not marked as @medium or @large. If a test does not complete within its configured timeout, it will fail.

Test Suites

The <testsuites> element and its one or more <testsuite> children can be used to compose a test suite out of test suites and test cases.

<testsuites>
  <testsuite name="My Test Suite">
    <directory>/path/to/*Test.php files</directory>
    <file>/path/to/MyTest.php</file>
    <exclude>/path/to/exclude</exclude>
  </testsuite>
</testsuites>

Using the phpVersion and phpVersionOperator attributes, a required PHP version can be specified. The example below will only add the /path/to/*Test.php files and /path/to/MyTest.php file if the PHP version is at least 5.3.0.

  <testsuites>
    <testsuite name="My Test Suite">
      <directory suffix="Test.php" phpVersion="5.3.0" phpVersionOperator=">=">/path/to/files</directory>
      <file phpVersion="5.3.0" phpVersionOperator=">=">/path/to/MyTest.php</file>
    </testsuite>
  </testsuites>

The phpVersionOperator attribute is optional and defaults to >=.

Groups

The <groups> element and its <include>, <exclude>, and <group> children can be used to select groups of tests marked with the @group annotation (documented in the section called “@group”) that should (not) be run.

<groups>
  <include>
    <group>name</group>
  </include>
  <exclude>
    <group>name</group>
  </exclude>
</groups>

The XML configuration above corresponds to invoking the TextUI test runner with the following options:

  • --group name

  • --exclude-group name

Whitelisting Files for Code Coverage

The <filter> element and its children can be used to configure the whitelist for the code coverage reporting.

<filter>
  <whitelist processUncoveredFilesFromWhitelist="true">
    <directory suffix=".php">/path/to/files</directory>
    <file>/path/to/file</file>
    <exclude>
      <directory suffix=".php">/path/to/files</directory>
      <file>/path/to/file</file>
    </exclude>
  </whitelist>
</filter>

Logging

The <logging> element and its <log> children can be used to configure the logging of the test execution.

<logging>
  <log type="coverage-html" target="/tmp/report" lowUpperBound="35"
       highLowerBound="70"/>
  <log type="coverage-clover" target="/tmp/coverage.xml"/>
  <log type="coverage-php" target="/tmp/coverage.serialized"/>
  <log type="coverage-text" target="php://stdout" showUncoveredFiles="false"/>
  <log type="json" target="/tmp/logfile.json"/>
  <log type="tap" target="/tmp/logfile.tap"/>
  <log type="junit" target="/tmp/logfile.xml" logIncompleteSkipped="false"/>
  <log type="testdox-html" target="/tmp/testdox.html"/>
  <log type="testdox-text" target="/tmp/testdox.txt"/>
</logging>

The XML configuration above corresponds to invoking the TextUI test runner with the following options:

  • --coverage-html /tmp/report

  • --coverage-clover /tmp/coverage.xml

  • --coverage-php /tmp/coverage.serialized

  • --coverage-text

  • --log-json /tmp/logfile.json

  • > /tmp/logfile.txt

  • --log-tap /tmp/logfile.tap

  • --log-junit /tmp/logfile.xml

  • --testdox-html /tmp/testdox.html

  • --testdox-text /tmp/testdox.txt

The lowUpperBound, highLowerBound, logIncompleteSkipped and showUncoveredFiles attributes have no equivalent TextUI test runner option.

  • lowUpperBound: Maximum coverage percentage to be considered "lowly" covered.

  • highLowerBound: Minimum coverage percentage to be considered "highly" covered.

  • showUncoveredFiles: Show all whitelisted files in --coverage-text output not just the ones with coverage information.

  • showOnlySummary: Show only the summary in --coverage-text output.

Test Listeners

The <listeners> element and its <listener> children can be used to attach additional test listeners to the test execution.

<listeners>
  <listener class="MyListener" file="/optional/path/to/MyListener.php">
    <arguments>
      <array>
        <element key="0">
          <string>Sebastian</string>
        </element>
      </array>
      <integer>22</integer>
      <string>April</string>
      <double>19.78</double>
      <null/>
      <object class="stdClass"/>
    </arguments>
  </listener>
</listeners>

The XML configuration above corresponds to attaching the $listener object (see below) to the test execution:

$listener = new MyListener(
  array('Sebastian'),
  22,
  'April',
  19.78,
  NULL,
  new stdClass
);

Setting PHP INI settings, Constants and Global Variables

The <php> element and its children can be used to configure PHP settings, constants, and global variables. It can also be used to prepend the include_path.

<php>
  <includePath>.</includePath>
  <ini name="foo" value="bar"/>
  <const name="foo" value="bar"/>
  <var name="foo" value="bar"/>
  <env name="foo" value="bar"/>
  <post name="foo" value="bar"/>
  <get name="foo" value="bar"/>
  <cookie name="foo" value="bar"/>
  <server name="foo" value="bar"/>
  <files name="foo" value="bar"/>
  <request name="foo" value="bar"/>
</php>

The XML configuration above corresponds to the following PHP code:

ini_set('foo', 'bar');
define('foo', 'bar');
$GLOBALS['foo'] = 'bar';
$_ENV['foo'] = 'bar';
$_POST['foo'] = 'bar';
$_GET['foo'] = 'bar';
$_COOKIE['foo'] = 'bar';
$_SERVER['foo'] = 'bar';
$_FILES['foo'] = 'bar';
$_REQUEST['foo'] = 'bar';

Configuring Browsers for Selenium RC

The following PHP code can be used to configure a list of Selenium RC servers:

class WebTest extends PHPUnit_Extensions_SeleniumTestCase
{
    public static $browsers = array(
      array(
        'name'    => 'Firefox on Linux',
        'browser' => '*firefox /usr/lib/firefox/firefox-bin',
        'host'    => 'my.linux.box',
        'port'    => 4444,
        'timeout' => 30000
      )
    );

    // ...
}