Function mocking with Patchwork 02

What has started as a side quest while toying with Patchwork ended as a promising tool, in its early stages, for function mocking. Static methods too.

GitHub

Since I’ve pushed the thing to GitHub I will copy and paste an extract of the README.md file content here.
In a perfect world you should never need to mock static methods and functions, should use TDD to write better object-oriented code and use it as a design tool.
But sometimes a grim and sad need to mock those functions and static methods might arise and this library is here to help.

// file SomeClass.php

class SomeClass {

    protected $postContent;

    public function __construct($postId) {
        // static method
        $this->postContent = Post::getPostContent($postId);

        if($this->postContent) {
            // function
            $this->postContent = manipulatePostContent($this->postContent);
        }
    }
}

as badly as it’s written it can be tested in a PHPUnit test case like

// file SomeClassTest.php   

use tad\FunctionMocker\FunctionMocker;

class SomeClassTest extends PHPUnit_Framework_TestCase {

    /**
     * @test
     */
    public function it_will_call_manipulatePostContent(){
        FunctionMocker::mock('Post::getPostContent', 'foo');
        $f = FunctionMocker::mock('manipulatePostContent');

        new SomeClass(23);

        $f->wasCalledWithTimes(['foo'], 1);
    }

}

When trying to mock instance method the FunctionMocker::mock will merely return a PHPUnit mock object acting, for all intents and purposes, as such

// file SomeClass.php

class SomeClass{

    protected $dep;

    public function __construct(Dep $dep){
        $this->dep = $dep;
    }

    public function someMethod(){
        return $this->dep->go();
    }
}

// file SomeClassTest.php   

use tad\FunctionMocker\FunctionMocker;

class SomeClassTest extends PHPUnit_Framework_TestCase {

    /**
     * @test
     */
    public function it_will_call_go(){
        $dep = FunctionMocker::mock('Dep::go', 23);

        $sut = new SomeClass($dep);

        $this->assertEquals(23, $sut->someMethod());
    }
}

The FunctionMocker::mock method will set up the PHPUnit mock object using the any method, the call above is equal to

$dep->expects($this->any())->method('go')->willReturn(23);

Next

I will add more sugar methods to the tool to allow more flexibility since I’m already using it with a degree of satisfaction.

I appreciate your input