Skip PHPUnit Tests Conditionally in PHP
Sometimes you may want to skip a PHPUnit test conditionally. For instance, you may want to skip a test if the PHP version is less than 7.4 or if a certain extension is not installed on the system.
I learned about this in this PR where the author wanted to skip all the tests if intl
extension is not installed on the system that’s because the code uses PHP’s NumberFormatter
class which is a part of intl
extension.
So, here’s how you can skip PHPUnit tests conditionally.
You define a method in the class where you check for the condition and if the condition is met, you call the markTestSkipped()
method (with a message) on the $this
object. This will skip the test.
protected function needsIntlExtension()
{
if (! extension_loaded('intl')) {
$this->markTestSkipped('The intl extension is not installed. Please install the extension to enable '.__CLASS__);
}
}
Then, you call this method in the setUp()
method of the test class or at the top of the test method itself.
public function setUp(): void
{
$this->needsIntlExtension();
}
That’s it. Now, if the intl
extension is not installed on the system, the test will be skipped.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.