The constructor in my class adds an action to the 'init' action hook:
class My_Custom_Post_Type {
function __construct( $type ) {
$this->type = $type;
add_action( 'init', array( $this, 'register_my_type' );
}
function register_my_type() {
register_post_type( $this->type);
}
}
I was trying to test this in a unit test and finally realized that there was no reason for the 'init' action hook to fire. Is there any way to test that the register_my_type method is being called and that a new post type is being registered?
Edit:
The main source of my confusion came from not understanding the relationship between phpunit, the WordPress test suite, my class code, and my test code.
What I now understand is that with the WordPress developer tools installed in the way the is suggested by this tutorial or through WP-CLI, a call to phpunit
loads a bootstrap file which then hooks the plugin into the muplugins_loaded
action hook. The bootstrap file then loads the WordPress test environment. After WordPress has finished loading the init
hook is run. Plugin code that makes use of init
should work as expected.
Tests are mostly just normal code that is making use of available functions or classes. What is different about them is that they are written as methods of a class that extends WP_UnitTestCase
which extends PHPUnit_Framework_TestCase
. Being wrapped in this class gives the tests access to assertions and object factories, and runs setUp
and tearDown
methods so that each test is independent of the others.