Testing function mocking with Patchwork

Function mocking with Patchwork

Ad hoc adapters are not necessary if function mocking is all that’s needed.

The problem

I’m trying to come up with an easy to use and adopt solution to write WordPress plugins and themes using TDD techniques and the pervasive use of globally defined functions in WordPress makes it difficult.
While playing around with patchwork I’ve tested if Patchwork could make it: it does very easily as seen in this PHPUnit tests

/**
 * @test
 * it should allow replacing non existing functions
 */
public function it_should_allow_replacing_non_existing_functions() {
    $function_name = 'undefined_function_1';
    $args = '$a, $b';

    eval( sprintf( 'function %s (%s){ return null; }', $function_name, $args ) );

    Patchwork\replace( $function_name, function () {
        return 'foo';
    } );

    $this->assertEquals( 'foo', undefined_function_1( 1, 2 ) );
}

/**
 * @test
 * it should allow replacing the same function multiple times in the same context
 */
public function it_should_allow_replacing_the_same_function_multiple_times_in_the_same_context() {
    $function_name = 'undefined_function_2';
    $args = '';

    eval( sprintf( 'function %s (%s){ return null; }', $function_name, $args ) );

    Patchwork\replace( $function_name, function () {
        return 'foo';
    } );

    $this->assertEquals( 'foo', undefined_function_2() );

    Patchwork\replace( $function_name, function () {
        return 'baz';
    } );

    $this->assertEquals( 'baz', undefined_function_2() );

    Patchwork\replace( $function_name, function () {
        return 'bar';
    } );

    $this->assertEquals( 'bar', undefined_function_2() );
}

The function mocker

While function mocking is not the way I will be walking as I will not mock interfaces I do not own (see Growing Object-Oriented Software Guided by Tests) I can see myself using it while working on pre-existing code and it seems so easy that I just can not pass.
That’s why I’ve pushed the project on GitHub.
Now that’s done being able to mock WordPress functions like this

FMocker::mock('get_post_meta', ['key1' => 'value1', 'key2' => 'value2']);

seems kind of a good possibility to work with WordPress based legacy code.

I appreciate your input