Unit testing wordpress plugins with plugin options

I’m new with unit testing in WordPress. I managed to setup the unit testing environment using PHP Unit and WordPress tests but I am having trouble accessing the plugin options that I’ve set in the plugin.

class nrw_pg{

  private $twitter_id;

  public function __construct(){
    $options = get_option('nrw_pg_options');
    $this->twitter_id = (!empty($options['nrw_pg_options_twitter_id'])) ? $options['nrw_pg_options_twitter_id'] : '';

  }

  public function get_tweets(){
     $result = null;
     $protocol = is_SSL() ? 'https://' : 'http://';
     $result = wp_remote_get($this->protocol . "api.twitter.com/1/statuses/user_timeline.json?screen_name=". $this->twitter_id."&count=11&exclude_replies=true");

     return $result;
   }
}

$GLOBALS['nrw_pg'] = new nrw_pg();

It all works smoothly when accessing it from the browser. But on the unit tests it doesn’t seem like it has knowledge of the options that I have set.

require_once('D:\web_files\tester\wordpress\wp-content\plugins\nrw_pg\nrw_pg.php');

class Nrw_Pg_Test extends WP_UnitTestCase {
    public $plugin_slug = 'nrw_pg';
    public $options;

    public function setUp() {
        parent::setUp();

        $this->nrw_pg = $GLOBALS['nrw_pg'];

    }

    public function test_get_tweets(){

        $this->assertNotNull($this->nrw_pg->connect());
    }

}

Is there anything else that I need to setup aside from the wp-test-config.php and other things mentioned here: https://stackoverflow.com/questions/9138215/unit-testing-wordpress-plugins in order to make this work?

It seems like other things are working like testing if specific filters are added. But the options it doesn’t seem like they have been initialized. Any ideas?

1 Answer
1

As the testing database is (usually, and should be) a separate database, you will need to set the appropriate option value in the setUp routine (using add_option or update_option).

I would also recommend deleting or reseting the option in the teardown method as well, but I have had issues when trying to drop tables (see Plugin development with unit tests).

Leave a Comment