0

I want to perform unit tests on a Class, my goal is: I want to check if the plugin is activated or not by using the function: is_plugin_active

class WC_Custom_Variable_Products_Dependencies {
    public function __construct() {
          add_action( 'admin_init', [$this, 'check_environment']);
    }
    public function check_environment(){
          return is_plugin_active( 
                    'woocommerce-custom-variable-products/woocommerce-custom-variable-products.php' 
                 );
    }
}

CLass de test :

require_once 'class-wc-custom-variable-products-dependencies.php';
class WC_Custom_Variable_Products_DependenciesTest extends WP_UnitTestCase {

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

        $this->class_instance = new WC_Custom_Variable_Products_Dependencies();
    }

    public function test_check_environment(){

        $result = $this->class_instance->check_environment();
        $this->assertTrue($result);
    }

The assertion return always False .

My plugin is activated, and the function is_plugin_active returns True if I execute it from the browser:

add_action('admin_init', function(){

     var_dump(is_plugin_active( 
                        'woocommerce-custom-variable-products/woocommerce-custom-variable-products.php' 
    ));
});

I think the admin_init hook is not executed in the test. is it true or not?

2
  • The hook you're testing doesn't make much sense, actions such as admin_init don't return values
    – Tom J Nowell
    Jan 10, 2020 at 2:36
  • The check_environment() method verify if the plugin is already active or not, so that's it hooked admin_init. I do not test the return value of admin_int, I test the check_environment() method.
    – Younes.D
    Jan 10, 2020 at 2:48

1 Answer 1

0

I found out why. here is the solution: you have to activate the plugin in the tests / bootstrap.php file:

$GLOBALS[ 'wp_tests_options' ] = array(
        'active_plugins' => array(
                'YOUR-PLUGIN/YOUR-PLUGIN.php'
        )
)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.