Juggling assertion syntax between PHPUnit versions

Josh Sherman
1 min read
Software Development PHP

I’m no stranger to the nuances of testing against different version of PHP and PHPUnit, but my previous issues were related to the environment itself. Recently I ran into an issue with different syntax between versions of PHPUnit, specifically assertRegExp() being deprecated, which was throwing an error.

Not only was assertRegExp() flagged as deprecated, the new syntax, expectNotToPerformAssertions() was not available in older version of PHPUnit.

Because I like to test my open source libraries against as many versions as humanly possible, that means I had to get creative to be able to use one set of syntax in older versions of PHPUnit, and the newer syntax in the newer versions.

While it’s not hard to sanity check the PHP version and use a variable variable for the method, PHPUnit does make it a pain to share variables between tests.

To help reduce the amount of code in my test suite, I went ahead and created a test without any assertions that returns which regular expression method we should be using, and made my other tests depend on it:

class UnitTest extends PHPUnit_Framework_TestCase
{
    /**
     * @doesNotPerformAssertions
     */
    public function testAssertRegExp() {
        if (version_compare(PHP_VERSION, '7.3.0', '>=')) {
            return 'assertMatchesRegularExpression';
        }

        return 'assertRegExp';
    }

    /**
     * @depends testAssertRegExp
     */
    public function testSomething($assertRegExp)
    {
        $this->$assertRegExp(...);
    }
}
Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

Related Articles