phpunit-testinglaravelmockery

Unit testing a closure in Laravel


The closure in the code below has made this code very difficult to test. How can I continue to eager load these items and maintain full testability?

public function scopeWithCompanyPreferences(Builder $builder)
{
    return $builder->with([
            'companies' => function ($query) {
                $query->with('companies');
                $query->with('preference_settings');
                $query->with('parent_company');
            }
        ]);
}

I've seen using Mockery the use of Mockery::on(), but I don't think that's useful given the array.


Solution

  • If you're mocking the with method, you should be able to use Mockery::on() like this:

    $b = \Mockery::mock("your_builder_class");
    $b->shouldReceive("with")
        ->with(\Mockery::on(function($x){
                // test $x any way you like, for example...
                // ...a simple check to see if $x["companies"] is a function
                return is_callable($x["companies"]);
            }))
        ->once()
        ->andReturn("hello!");