Skip to content

Instantly share code, notes, and snippets.

@odan
Last active March 29, 2023 12:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odan/5bfe3e16dfafa98b61ff3da10f373d13 to your computer and use it in GitHub Desktop.
Save odan/5bfe3e16dfafa98b61ff3da10f373d13 to your computer and use it in GitHub Desktop.
Mocking Interfaces with PHPUnit

Mocking Interfaces with PHPUnit

Using the MockBuilder

To mock an interface with PHPUnit we have to pass all methods of the given Interface.

 $reflection = new \ReflectionClass(UserRepositoryInterface::class);

$methods = [];
foreach($reflection->getMethods() as $method) {
    $methods[] = $method->name;
}
$stub = $this->getMockBuilder(UserRepositoryInterface::class)
    ->setMethods($methods)
    ->getMock();

$stub->method('findAll')->willReturn([new UserData()]);

The downside is, that your tests will fail if you rename a interface method, because findAll is just an string an cannot be automatically renamed / refactored by PhpStorm in this way.

Using anonymous classes

Using anonymous classes is more refactor-friedly and works without reflection.

$stub = new class() implements UserRepositoryInterface
{
    public function findAll(): array
    {
        return ['my' => 'data'];
    }
    public function getUserById(int $userId): UserData
    {
        // TODO: Implement getUserById() method.
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment