WordPress Unit Testing: Deprecated Functions

A new feature has just been introduced into the WordPress test suite: the @expectedDeprecated notation. This notation is modeled after PHPUnit’s built-in @expectedException notation, and allows you to test for the use of deprecated functions or function arguments in your test suites. (You do have a suite of unit tests for your plugin, don’t you?)

This new feature comes as the result of a charge to clean up the WordPress unit tests, lead by @wonderboymusic. I’m really glad to see this happen, because the tests, like any WordPress development environment, really should be run with WP_DEBUG on, and when I tried that a few weeks ago I encountered plenty of notices. Many of those notices were about the use of deprecated functions in the test suite. The use of these functions is intentional, and is meant to test for backward compatibility. The new notation provides a way to test deprecated functions, and at the same time test that the proper deprecated notices are given. Also as a result of this, any time a deprecated function is used in a suite and it hasn’t been @expectedDeprecated, the test will fail. Tests which expect deprecated notices and don’t get them will also fail.

The usage of this new annotation is simple enough. If you have a test case that uses a deprecated function or argument, then add an @expectedDeprecated to the docblock for the test function where the deprecated function or function argument is used. In the below example, we’ll test one of your project’s functions that has been deprecated, and another that has a deprecated argument:

<?php

/**
 * A test case.
 *
 * In case we fail, we test.
 */
class My_Deprecated_Function_Test extends WP_UnitTestCase {

	/**
	 * Test these this deprecated functions are backward compatible.
	 *
	 * They have to give deprecated notices too, or else this won't pass.
	 *
	 * @expectedDeprecated my_deprecated_function
	 * @expectedDeprecated function_with_deprecated_arg
	 */
	public function test_my_deprecated_function() {
	
		$this->assertTrue( my_deprecated_function() );
		$this->assertEquals( 4, function_with_deprecated_arg( 'deprecated' ) );
	}
}

You can also use this when testing for backward compatibility with older versions of WordPress, by marking any deprecated WordPress functions used as @expectedDeprecated.

The notation can also be used in the class docblock, if all of your tests in a test case class will be using the deprecated function.

One thought on “WordPress Unit Testing: Deprecated Functions

  1. Pingback: WordPress Unit Test Suite Introduces @expectedIncorrectUsage | Code Symphony

Leave a Reply

Your email address will not be published. Required fields are marked *