To configure PHPUnit, you need to follow these steps:
- Install PHPUnit: First, you need to install PHPUnit on your system. PHPUnit is available as a Composer package, so you can install it globally or on a per-project basis. To install it globally, run the following command:
composer global require phpunit/phpunit
Alternatively, you can install it locally by running the command within your project’s directory without the global
flag.
- Create a configuration file: PHPUnit requires a configuration file named
phpunit.xml
orphpunit.xml.dist
to define the test suite, test directories, and other settings. You can create this file in the root directory of your project. You can either create the file manually or generate it using thephpunit --generate-configuration
command.
vendor/bin/phpunit --generate-configuration
- Configure the XML file: Open the
phpunit.xml
file and configure it according to your project’s needs. The configuration file uses XML format, and you can set various options such as the test suite, test directories, bootstrap files, logging, and more. Customize the configuration file to match your project’s structure and requirements. Here’s an example of a basic configuration:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.5/phpunit.xsd" bootstrap="tests/bootstrap.php">
<testsuites>
<testsuite name="My Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>
In this example, the bootstrap
attribute points to a bootstrap file (bootstrap.php
) that is executed before the tests run. The <testsuite>
element specifies the test suite name and the directory where your tests are located (tests
in this case).
- Run PHPUnit: Once you’ve configured PHPUnit, you can run it from the command line. Make sure you are in the project’s root directory, and then run the following command:
phpunit
PHPUnit will read the phpunit.xml
configuration file and execute the tests based on the defined settings.
You can also pass specific options or filter tests to run. For example:
phpunit --filter MyTestClassName
This command will only run tests from the class MyTestClassName
.
That’s it! You have now configured PHPUnit for your project. You can write your tests in separate PHP files within the specified test directories and execute them using PHPUnit.