How to use PHPUnit's annotations and attributes for test configuration?

PHPUnit's annotations and attributes can be used for test configuration in the following way:

  1. Configure the PHPUnit bootstrap file:

    • Create a file named phpunit.xml (or phpunit.xml.dist) in the root directory of your project.
    • Add the following XML snippet to the phpunit.xml file:
    <phpunit bootstrap="vendor/autoload.php"> <!-- Additional configuration --> </phpunit>
    • Replace vendor/autoload.php with the path to your vendor/autoload.php file if different.
  2. Add annotations or attributes to your test cases:

    • Annotations: Annotations are added as PHP comments directly above the test method or test case class.
    /** * @dataProvider dataProviderMethod * @group group1 */ public function testExample($param1, $param2) { // Test logic }
    • Attributes: Attributes are supported in PHPUnit 9 and above and can be added directly to the test method or test case class.
    #[Test(attrs: ['dataProvider' => 'dataProviderMethod'], groups: ['group1'])] public function testExample($param1, $param2) { // Test logic }
  3. Run the tests:

    • Run the PHPUnit command from the command line, pointing it to your phpunit.xml file:
    $ vendor/bin/phpunit
    • PHPUnit will read the annotations/attributes and apply the specified configuration, such as data providers, test groups, etc.

By using PHPUnit's annotations and attributes, you can easily configure your tests and control their behavior without modifying the test case code itself.