Function mocking with Patchwork 05

Function mocking gets easier using the extended test case.

Explicit mock verification

Needing to verify that the mock expectation would throw when not fulfilled I’ve implemented function-mocker to allow for test cases like this:

class SomeClassTest extends \PHPUnit_Framework_TestCase {
        public function functionExpectations() {
        return array(
            // times, calls, shouldThrow
            array( 3, 2, true ),
            array( 3, 3, false ),
            array( 0, 1, true),
            array( 0 , 0, false)
        );
    }

    /**
     * @test
     * it should allow setting expectations on mocked functions
     * @dataProvider functionExpectations
     */
    public function it_should_allow_setting_expectations_on_mocked_functions( $times, $calls, $shouldThrow ) {
        if ( $shouldThrow ) {
            $this->setExpectedException( '\PHPUnit_Framework_AssertionFailedError' );
        }

        FunctionMocker::mock( __NAMESPACE__ . '\someFunction' )->shouldBeCalledTimes( $times );

        for ( $i = 0; $i < $calls; $i ++ ) {
            someFunction();
        }

        // explicitly verify
        FunctionMocker::verify();
    } 
} 

where I’m using PHPUnit_Framework_TestCase as my test case parent class, PHPUnit stock one, and will have to explicitly trigger the mock verifications to see the test pass or fail as expected.

Using assertPostConditions in custom test case

Using the function mocker test case, TestCase, I can tap into PHPUnit API to automatically assert that mock expectations have been met writing slimmer test cases like this:

class SomeClassTest extends tad\FunctionMocker\TestCase {

    /**
     * @test
     * it should allow setting expectations on mocked functions
     */
    public function it_should_allow_setting_expectations_on_mocked_functions() {
        FunctionMocker::mock( 'someFunction' )->shouldBeCalledTimes( 3 );

        someFunction();
        someFunction();
    } 

} 

Having verified that the FunctionMocker::verify method will, in fact, verify expectations on mock objects I’m just doing that in the custom test case:

namespace tad\FunctionMocker;

class TestCase extends \PHPUnit_Framework_TestCase {

    public function assertPostConditions() {
            FunctionMocker::verify();
        // and any other verfication
    }
}

Verifications made here will affect the test result and contribute to the test passing/failing condition.
Kudos to PHPUnit.

I appreciate your input