Skip to content

ClosureUsesThisRule produces false positive with Prophecy will() #142

@InvisibleSmiley

Description

@InvisibleSmiley

If you replace $that by $this in the closure of the following, the test will fail.

At runtime, the type of $this is \Prophecy\Prophecy\ObjectProphecy and the type of $that is MyTest.

<?php

declare(strict_types=1);

// Requires phpunit/phpunit, phpspec/prophecy and phpspec/prophecy-phpunit

namespace foo;

use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;

class MyTarget
{
    public function run(string $input): string
    {
        return $input;
    }
}

class MyTest extends TestCase
{
    use ProphecyTrait;

    private array $stuff = ['foo' => 'bar'];

    public function testMyMock(): void
    {
        $prophecy = $this->prophesize(MyTarget::class);
        $that = $this;
        $prophecy->run(Argument::type('string'))->will(
            function (array $args) use ($that): string {
                return $that->stuff[$args[0]] ?? $args[0];
            }
        );
        $target = $prophecy->reveal();
        $result = $target->run('foo');
        self::assertSame('bar', $result);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions