WordPress Unit Test Suite Introduces @expectedIncorrectUsage

In an recent effort to clean up the WordPress unit tests, the @expectedDeprecated notation was introduced for testing deprecated functions. Now another new notation was introduced which does a similar thing for _doing_it_wrong(). Usually, you don’t want to be _doing_it_wrong(), but you might want to test that the proper warning is given from your code when someone does it wrong. And that is where @expectedIncorrectUseage comes into play. Now your tests will fail if you are _doing_it_wrong(), which is helpful to make sure you are coding your project correctly. But when you are testing for a _doing_it_wrong(), you are expecting it, so you can add the @expectedIncorrectUsage to your tests. Then your test will fail if you don’t receive the expected _doing_it_wrong() warning.

The usage is simple:

<?php

/**
 * A test class with failing tests.
 */
class Failing_WP_UnitTestCase extends WP_UnitTestCase {

	/**
	 * This test will succeed, because we were expecting to do it wrong.
	 *
	 * @expectedIncorrectUseage register_uninstall_hook
	 */
	public function test_with_expected_incorrect_usage() {
		
		// Only static functions can be registered as an uninstall callback.
		register_uninstall_hook( __FILE__, array( $this, 'a_function' ) );
	}
	
	/**
	 * This test will fail, because we weren't expecting to do it wrong.
	 */
	public function test_with_expected_incorrect_usage() {
		
		// Only static functions can be registered as an uninstall callback.
		register_uninstall_hook( __FILE__, array( $this, 'a_function' ) );
	}
	
	/**
	 * This test will fail, because we don't do this wrong, though it was expected.
	 *
 	 * @expectedIncorrectUseage register_uninstall_hook
	 */
	public function test_with_expected_incorrect_usage() {
		
		// Only static functions can be registered as an uninstall callback.
		register_uninstall_hook( __FILE__, array( __CLASS__, 'a_function' ) );
	}
}

This will be useful for those that are heavily using the WordPress unit test framework, like running plugin unit tests.

Leave a Reply

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