Mocking filters in WordPress unit tests

Mocking filters in WordPress unit tests with Function Mocker.

Mocking WordPress filters

I should rather say “mocking WordPress functions” or, in the really general sense, “mocking user-land functions” but I will stick to my main context and appreciate what function-mocker can do for my WordPress unit tests right now:


use tad\FunctionMocker\FunctionMocker as Test;
    
    class myTest extends \PHPUnit_Framework_TestCase {
    
        function my_filter_test(){

            Test::replace( 'apply_filters', function ( $tag, $val ) {

                // all filters will passthru but the one I want to mock
                return $tag == 'trc_user_can_access_query' ? false : $val;
            } );

                // test using the filter here...
        }

    }

I’ve been asked for some examples of how I use it while at WordCamp Europe and here they are.
Beside cases where the mock function can just return a fixed primitive value I will leverage the power that function-mocker offers to set closure-based return values; the example below is to return different values based on the filter tag:


use tad\FunctionMocker\FunctionMocker as Test;
    
    class myTest extends \PHPUnit_Framework_TestCase {
    
        function my_filter_test(){

            Test::replace( 'apply_filters', function ( $tag, $val ) {
                $map = [
                    'filter_tag_1' => false,
                    'filter_tag_2' => 'foo',
                    'filter_tag_3' => 23
                ];

                return isset($map[$tag]) ? $map[$tag] : $val;
            } );

                // test using the filter here...
        }

    }


What’s the benefit? No headless WordPress instance running, no database connection needed, speed… unit tests.