Behzadsh
Behzadsh

Reputation: 870

How to test data passed to closure, with phpunit

I have a class, which generate a data object and pass it to given callable variable

<?php

class Foo {

    public function bar(callable $closure)
    {
        $data = $this->generateData();

        call_user_func_array($closure, compact($data));
    }

}

// example usage
$baz = new Foo()
$baz->bar(function($data) {
    var_dump($data); // I want to test $data type inside this closure
});

How can I test $data dataType pass to the anonymous function?

Upvotes: 1

Views: 1995

Answers (1)

Ondřej Mirtes
Ondřej Mirtes

Reputation: 5661

$baz = new Foo();
$baz->bar(function($data) {
    $this->assertSame('expected', $data);
});

Also make sure that your closure is even called, probably by setting a variable:

$baz = new Foo();
$called = false;
$baz->bar(function($data) use (&$called) {
    $called = true;
    $this->assertSame('expected', $data);
});
$this->assertTrue($called);

Upvotes: 4

Related Questions