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 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.
}
};