27 September 2014

When we set up WordPress-PhpUnit Environment, to automate test-cases for our plugin/theme (mainly plugins, I’ve not come across any WP theme which has test cases written for it), we either set it up manually or we take help of WP-CLI to build the scaffolding of our plugin. WordPress has an amazing testcase wrapper class for PhpUnit that can be used when we make out plugin testable.

Of course, when our plugin does not deal with database then we do not have to worry about as our plugin will only make use of the readily available tables of WordPress and there will not be any need to introduce new database tables. But if we deal with database tables through our plugin then we need these tables when we perform test-cases using PhpUnit. wpdb & dbDelta gives you enough power to play with database tables in your plugin. But when we are in PhpUnit environment, schematics are a bit different. WordPress testcase wrapper creates temporary DB tables in WordPress PhpUnit environment. What this means is when we execute test-cases for our plugin, the built-in wrapper class - mentioned before - tells WordPress to create temporary (virtual) tables in MySql and NOT permanent (actual) tables (Reference). Because of this, your test-cases related DB tables will only exist during the PhpUnit execution. They will be destroyed from the memory.

The sole purpose of such mechanism is to keep the test data away from the database and not bloat the memory with corrupt data, keeping the database intact. If this is the case then you’re good to go; but there are times when we can’t move ahead and believe that everything is working absolutely fine until we see the actual results :wink:. We might need those database table to retain its state even after the PhpUnit execution. In that case we can use following solution:

Override setUp method of WP_UnitTestCase class in your own testcase class. The method definition should look as follows:

function setUp() {
	// Perform the actual task according to parent class.
	parent::setUp();
	// Remove filters that will create temporary tables. So that permanent tables will be created.
	remove_filter( 'query', array( $this, '_create_temporary_table' ) );
	remove_filter( 'query', array( $this, '_drop_temporary_table' ) );
}

Above code will do the trick. Happy coding & testing ! :smile:


Categories: Tags:

blog comments powered by Disqus