mardi 10 septembre 2019

php mockery execute callback without passthru

class Something {
   public function methodWithCallback($param, $callback) {
      echo 'method '.$param.PHP_EOL;
      $callback('world');
   }
}

normal call:

(new Something)->methodWithCallback('hello', function($param) {
    echo 'cb '.$param.PHP_EOL;
});

output:

method hello
cb world

How can I mock it so the method is not excuted, but the callback is with a value that I provide to the mock.

I would think of something like:

$mock = Mockery::mock(Something::class)
->shouldReceive('methodWithCallback')
->andExecuteArgument(1)->using('world')

$mock->methodWithCallback('hello', function($param) {
        echo 'cb '.$param.PHP_EOL;
    });

Expected output:

cb world

The closest I could get was using passthru, but this actually executes the code in the method which I try to avoid.

Aucun commentaire:

Enregistrer un commentaire