What is the best way to create a factory for unit test objects?

If I undertsand correctly, what you are searching for is a good library for creating stubs and mocks. If you use PHPUnit, it has a features for that. See https://phpunit.de/manual/current/en/test-doubles.html#test-doubles For example, let’s assume you have a class like this: namespace MyApp; class MyCustomUser { public function __construct(\WP_User $user) { $this->user = $user; } public … Read more

Unit Test in WordPress

Take a look at the WordPress core setup with PHPUnit: https://make.wordpress.org/core/handbook/testing/automated-testing/phpunit/ Using this process rather than rolling your own allows you to leverage the boostrapping (and other customization) specific for WordPress. From the Codex: When phpunit is invoked, the test suite runs a script that sets up a default installation of WordPress, with a configuration … Read more

How to initialize something in unit test before the init hook being called?

What you have discovered is that WordPress is loaded—and all of the actions are called—before the tests run. It is possible to hook into an action when WordPress is loaded, but it has to be done from your PHPUnit bootstrap file instead of from the testcase class. I don’t know what your bootstrap file looks … Read more