I’ve been writing more unit tests of late and have been running into some interesting issues when working with WordPress plugins.
If you’re just getting started with unit testing I can highly recommend the following articles/turorials/videos to help you along:
- https://pippinsplugins.com/unit-tests-wordpress-plugins-setting-up-testing-suite/
- http://taylorlovett.com/2014/07/04/wp_unittestcase-the-hidden-api/
- https://www.youtube.com/watch?v=84j61_aI0q8
My problem was that I wanted to define a couple of things in the setUp() method in my testing class using the factory() method of WP_UnitTestCase, but $this->factory() was null.
The quick fix was to explicitly call parent::setUp() before attempting to use the factory method in my own class.
This didn’t work:
<?php
class Test_NID_RSS_Importer extends WP_UnitTestCase {
public $user_id = null;
public function setUp() {
$this->user_id = $this->factory->user->create( array( 'user_login' => 'test', 'role' => 'administrator' ) );
}
public function test_something() {
$this->user_id; // Do some tests!
}
}
But this does:
<?php
class Test_NID_RSS_Importer extends WP_UnitTestCase {
public $user_id = null;
public function setUp() {
parent::setUp(); // Aha!
$this->user_id = $this->factory->user->create( array( 'user_login' => 'test', 'role' => 'administrator' ) );
}
public function test_something() {
$this->user_id; // Do some tests!
}
}