简体   繁体   中英

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.

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!");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM