Brain-WP/BrainMonkey

Test plugin main file (outside of a class)?

Closed this issue · 2 comments

In the plugin main file I have this

<?php
namespace My_Plugin;

require __DIR__ . '/vendor/autoload.php';

function activate() {
  Includes\Activator::activate();
}

register_activation_hook( __FILE__, __NAMESPACE__ . '\\activate' );

function init_plugin() {
  $plugin = new Includes\Main();
  $plugin->run();
}

init_plugin();

I'm kinda following the plugin boilerplate to an extent. Running phpunit makes require, the inside of activate() function, register_activation_hook and init_plugin red (untested).

But since they are outside any class, I'm not 100% sure how to test them :S

Especially require, since that is a language construct.

Should I use Filters\expectApplied on the register_activation_hook?

Hi @dingo-d,
sorry for late answer, just back from my vacation.

Main plugin files are by definition side-effectful and non-unit, as they connect stuff together, so it is not really something that you can test in a unit test.

If you write some integration test (loading WordPress) than you can test that the plugin main plugin works, by checking that on activation the activator does its job (whatever it is) and that bottstrapping procedure runs...

However, because all the code you posted could be summarized in these 3 lines:

require __DIR__ . '/vendor/autoload.php';

register_activation_hook( __FILE__, [My_Plugin\Includes\Activator::class, 'activate'] );

(new My_Plugin\Includes\Main())->run();

and because you can assume that both require and register_activation_hook work, if you separately unit-test Includes\Activator::activate() and Includes\Main::run()... that should be enough to ensure your main plugin will work...

Awesome, thanks! I'm running unit tests on methods that I can unit test - mostly methods that return something so I can mock and test the functionality, and I run separate integration tests on things that really cannot be mocked - like update_user_meta for instance, or similar functionality.

I'll just test this in the integration tests and find a way to combine my coverage.