Pass in Closure for Hooks
Feature request
At the moment we can currently pass a Closure as the return value when mocking functions using the \WP_Mock::userFunction like so:
WP_Mock::userFunction(
'get_post_meta',
[
'times' => 3,
'return' => function( $post_id, $key, $single ) {
if ( $key === 'some_meta_key' ) {
return 'some value';
}
return 'another value';
}
]
);
This really comes in handy when we are in a loop situation and we need to do this several times.
Proposed solution
Can this same approach be employed for hooks? It would be very handy to do this in one swoop, just like its userFunction counterpart.
WP_Mock::expectFilter(
'custom_post_types',
[
'times' => 3,
'return' => function( $post_type ) {
return $post_type
}
]
)
hey @badasswp thanks for bringing this up
At the moment it should be possible to write something like
WP_Mock::expectFilter('wp_title', function() {
return 'My Title';
}, 10, 2);
You can also perform the following assertion:
WP_Mock::expectFilterAdded('wp_title', WP_Mock\Functions::type(\Closure::class), 10, 2);
I understand that you might be interested perhaps in determining whether the returned value is expected according to the logic applied by the callback. In these circumstances you could perhaps invoke a protected method from the closure, like so:
add_filter('wp_title', function() { $this->myProtectedMethod(); });
And then create a proper test for myProtectedMethod for more flexibility and isolation.
See the documentation for more examples with hooks: https://wp-mock.gitbook.io/documentation/usage/mocking-wp-action-and-filter-hooks
Please let me know if this is helpful.
Thank you for your response @unfulvio-godaddy
My main point was around using Closures to dynamically return values multiple times, just like the userFunction static method. In this way, we wouldn't have to write multiple expectations for loop or iteration scenarios.
The previous examples you have described above was a bit close, but doesn't quite capture what I'm trying to achieve. This is what I'm trying to achieve:
WP_Mock::expectFilter(
'custom_post_types',
[
'times' => 3,
'return' => function( $post_type ) {
return $post_type
}
]
)
I see, this unfortunately would require some refactoring or breaking change, because right now the expectFilter function can accept a variable number of arguments as outlined in my examples before and passing an array as in your proposed example is not expected. Maybe passing an array should short circuit this line https://github.com/10up/wp_mock/blob/1.0.0/php/WP_Mock.php#L260 and account for a different behavior with the count passed to this line https://github.com/10up/wp_mock/blob/1.0.0/php/WP_Mock.php#L257 -- internally as you can see it already returns the pass-through value