formapro / Fumocker

A php function mocker.
MIT License
7 stars 1 forks source link

Support mocking anonymous functions #19

Open igorw opened 12 years ago

igorw commented 12 years ago

I have a few libraries that use anonymous functions. I've come up with a nice way to mock them, maybe you can add support for this in fumocker.

The base mock class is simply a class that implements __invoke:

namespace Igorw\Tests\SocketServer;

class CallableMock
{
    public function __invoke()
    {
    }
}

In the tests you can then simply mock that class and use it as a function:

private function expectCallableExactly($amount)
{
    $mock = $this->createCallableMock();
    $mock
        ->expects($this->exactly($amount))
        ->method('__invoke');

    return $mock;
}

private function expectCallableOnce()
{
    $mock = $this->createCallableMock();
    $mock
        ->expects($this->once())
        ->method('__invoke');

    return $mock;
}

private function expectCallableNever()
{
    $mock = $this->createCallableMock();
    $mock
        ->expects($this->never())
        ->method('__invoke');

    return $mock;
}

private function createCallableMock()
{
    return $this->getMock('Igorw\Tests\SocketServer\CallableMock');
}

What do you think? It would be nice to have this in a re-usable library.

makasim commented 12 years ago

It is not the case.

It is a good idea to keep this stuff close at hand but the problem is in that there is nothing to do with mocking function itself. Since we choose Unix way we prefer to keep it simple and do just one job. In case of adding your code, Fumoker would depend more tied on Phpunit. What about those who use SimpleTest or Mockery?

igorw commented 12 years ago

I was under the impression that fumocker already depends on PHPUnit's PHPUnit_Framework_MockObject_Generator. But maybe this is the wrong project to add this stuff to. I just don't think that I will be able to get it into PHPUnit core.

makasim commented 12 years ago

We have a relation to Phpunit and It is not what we are proud of. We haven't found a better solution for that so far.