How to skip certain tests in PHPUnit?

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

How to skip certain tests in PHPUnit?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 10 months ago

@cali_green 

There are a few different ways to skip certain tests in PHPUnit:

  1. Using the @group annotation: You can assign tests to different groups using the @group annotation in the test method's docblock. Then, during test execution, you can exclude certain groups using the --exclude-group command line option. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public function test1(): void
{
    $this->markTestSkipped('This test is skipped for now.');
}

/**
 * @group slow
 */
public function test2(): void
{
    // Test implementation
}


To skip the test1 test method, you can run PHPUnit with the --exclude-group slow command line option.

  1. Using the @requires annotation: You can use the @requires annotation to skip tests based on certain conditions. For example, you can skip a test if a specific PHP extension is not available:
1
2
3
4
5
6
7
/**
 * @requires extension mysql
 */
public function test(): void
{
    // Test implementation that requires the "mysql" extension
}


The test will be skipped if the mysql extension is not available.

  1. Using conditional logic within the test method: You can also skip tests based on certain conditions within the test method itself. You can use the markTestSkipped() method to skip the test programmatically based on certain conditions. For example:
1
2
3
4
5
6
7
8
public function test(): void
{
    if (!extension_loaded('mysql')) {
        $this->markTestSkipped('This test requires the "mysql" extension.');
    }

    // Test implementation
}


The test will be skipped if the mysql extension is not available.


These are some of the ways you can skip certain tests in PHPUnit. Choose the one that best suits your needs based on the specific conditions you want to skip the tests for.