rodion.arr
rodion.arr

Reputation: 111

Mock non-existing class in PHPUnit 10

Before PHPUnit 10 it was possible to mock non-existing class using next code:

    $this->getMockBuilder('NonExistentClass')
            ->setMethods(['__invoke'])
            ->getMock();

In PHPUnit 10 the setMethods() is going to be removed: https://github.com/sebastianbergmann/phpunit/issues/3769

New MockBuilder API introduced addMethods() method which is using Reflection inside and does not allow to work with non-existing classes anymore.

Please advise how we can create mocks for non-existing class with new API

Upvotes: 3

Views: 1003

Answers (2)

Robin
Robin

Reputation: 9644

You can mock \stdClass as the base class:

$mock = $this->getMockBuilder(\stdClass::class)->addMethods(['__invoke'])->getMock();

Upvotes: 4

rodion.arr
rodion.arr

Reputation: 111

I finished with next solution:

  • in my tests folder I've created an empty "physical" class:
<?php

namespace Tests\Helpers;

class EmptyCallableClass
{
    public function __invoke()
    {
    }
}

  • then in my tests I can mock it like all others classes (example from Laravel):
<?php

namespace Tests\Unit;

use PHPUnit\Framework\MockObject\MockObject;
use Tests\Helpers\EmptyCallableClass;
use Tests\TestCase;

class LravelMiddlewareTest extends TestCase
{
    /**
     * @var MockObject
     */
    private $closureMock;

    public function setUp(): void
    {
        $this->closureMock = $this->createPartialMock(EmptyCallableClass::class, ['__invoke']);
    }
}

Upvotes: 0

Related Questions