How to group PHPUnit tests into categories?

Member

by mac , in category: PHP General , a year ago

How to group PHPUnit tests into categories?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , a year ago

@mac 

To group PHPUnit tests into categories, you can make use of test suites. Test suites allow you to organize your tests into logical groups, making it easier to run specific categories of tests.


Here's a step-by-step guide to grouping PHPUnit tests into categories using test suites:

  1. Create a new test suite class or modify an existing one.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// tests/MyTestSuite.php

use PHPUnitFrameworkTestSuite;

class MyTestSuite extends TestSuite
{
    public static function suite()
    {
        $suite = new self();
        
        // Add individual test classes to the suite
        $suite->addTestSuite(MyCategory1Test::class);
        $suite->addTestSuite(MyCategory2Test::class);
        
        // Add other test suites if needed
        $suite->addTestSuite(OtherTestSuite::class);

        return $suite;
    }
}


  1. Create individual test classes for each category you want to group.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// tests/MyCategory1Test.php

use PHPUnitFrameworkTestCase;

class MyCategory1Test extends TestCase
{
    public function testSomething()
    {
        // Test logic
    }

    // Add more tests specific to this category
}


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// tests/MyCategory2Test.php

use PHPUnitFrameworkTestCase;

class MyCategory2Test extends TestCase
{
    public function testSomethingElse()
    {
        // Test logic
    }

    // Add more tests specific to this category
}


  1. Modify your phpunit.xml configuration file to use the test suite.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12


    

    
        
            ./tests
            ./tests/MyTestSuite.php
        
    


  1. Run PHPUnit with the name of the test suite.
1
$ vendor/bin/phpunit --testsuite "My Test Suite"


This will execute all the tests within the specified test suite, grouping them logically based on the categories you defined. You can create multiple test suites and categorize your tests accordingly to suit your needs.