Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing async methods with PHPUnit

Tags:

php

phpunit

I tried using a sleep and try approach. But it fails sometimes. What is the standard? Can't find anything obvious around. Thanks.

function foo($callback)
{
    $bar->asyncCall($callback);
}

function testFoo()
{
    $semaphore = 1;
    foo(function() {
        $semaphore = 0;
    });
    sleep(5) until $semaphore == 0;
}

With this approach testFoo() sometimes never returns. I suspect a deadlock somewhere.

like image 677
Bonton255 Avatar asked May 22 '26 15:05

Bonton255


1 Answers

The way php scopes variables, you are not changing the same $semaphore variable in your test. You are creating a new variable in the anonymous method you pass to foo(...).

You would need to mark the var with the use keyword.

function testFoo()
{
    $semaphore = 1;
    foo(function() use ($semaphore) {
        $semaphore = 0;
    });
    $this->assertEquals(0, $semaphore);
}

No need for the sleep then since this is not asynchronous from what we can see from here. More info on the $bar->asynCall() would be needed. See more on variable scope here: http://php.net/manual/en/functions.anonymous.php

like image 89
user1777136 Avatar answered May 26 '26 15:05

user1777136



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!