Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closure provided by data provider is bound to different object at test time #3097

Closed
Bilge opened this issue Apr 16, 2018 · 1 comment
Closed

Comments

@Bilge
Copy link
Contributor

Bilge commented Apr 16, 2018

Q A
PHPUnit version 6.5.8
PHP version 7.1.6
Installation Method Composer
    private $foo;

    protected function setUp(): void
    {
        $this->foo = new \Exception('foo');
    }

    /**
     * @dataProvider provideClosure
     */
    public function test(\Closure $closure): void
    {
        $closure();
    }

    public function provideClosure(): \Generator
    {
        yield [function () { return $this->foo->getMessage(); }];
    }

Error : Call to a member function getMessage() on null

This doesn't work because whatever the Closure is bound to at test setup time (when provideClosure() is invoked) is not the same object as when test() is invoked. The only way around this is to rebind the closure when it is invoked, i.e. do the following:

    /**
     * @dataProvider provideClosure
     */
    public function test(\Closure $closure): void
    {
        // Workaround: rebind closure to this test instance.
        \Closure::bind($closure, $this)();
    }

If possible, closures created by data providers should be bound to the same test instance as the test class they were created by, to avoid betraying user's expectations and having to employ this ugly workaround.

@sebastianbergmann
Copy link
Owner

This is, I am afraid, expected behavior for now and you need that workaround.

All data providers are executed before the first test is run. Hopefully, eventually this will change. This is what #10 is about.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants