How to properly test a method that is called by an action hook

Let me start by saying that the init action is called when WordPress is loaded, before the tests are run. So it you are having your plugin/theme loaded with WordPress (by hooking into muplugins_loaded, for example), the register_my_type() method should be getting called, if your constructor is being called before init. (If you aren’t loading your plugin that way, have a look at this tutorial.)

So in your unit tests you should be able to do this:

$this->assertTrue( post_type_exists( 'my_post_type' ) );

You could also use get_post_type() to check that the post type was registered with the correct arguments. (This is the same sort of thing I do to check that my shortcodes are registered.)

I wouldn’t worry about trying to test that the method was called, although you could check the list of actions in $wp_actions to see if it was hooked up properly. You could also set a class property as a flag when it is called, but I really think all of that’s overkill. When it comes to things hooked to actions like init, especially a function like this which only needs to run once, functional tests are your best bet. Check that they’ve done what they’re supposed to do, rather than focusing on trying to test a single unit like whether the method was called.

That said, you could also test that the method registers the post type by deregistering the post type and manually calling the method. WordPress doesn’t appear to provide a deregister_post_type() function, so you’d have to mess with the $wp_post_types global directly. You could delete your post type from that and then call your method and check if it is registered again.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)