Php Laravel-如何在模型上正确模拟/存根方法

Php Laravel-如何在模型上正确模拟/存根方法,php,laravel,phpunit,Php,Laravel,Phpunit,如何在模型上正确地模拟/存根方法(在laravel中)?目前我正在尝试 $mock = Mockery::spy(Organisation::class); $mock->shouldReceive('findByCustomerId')->once(); 测试中的代码是 use App\Organisation; ... public function handle() { $org = Organisation::findByCustomerId(1234); 然而

如何在模型上正确地模拟/存根方法(在laravel中)?目前我正在尝试

$mock = Mockery::spy(Organisation::class);
$mock->shouldReceive('findByCustomerId')->once();
测试中的代码是

use App\Organisation;
...
public function handle()
{
     $org = Organisation::findByCustomerId(1234);

然而,当我运行测试时,我得到一个错误调用,调用了未定义的方法App\organization::findByCustomerId(),它告诉我类/模型没有被正确地模拟,有人知道我可能会出错吗?

在为类创建模拟时,Mockry不会自动重载类它确实支持,但我不知道如何用部分模拟重载类

因此,看起来您必须使用依赖项注入将模拟对象“注入”到正在测试的类中:

class TestedClass
{
    private $organisation;

    public function __construct(Organisation $organisation)
    {
        $this->organisation = $organisation;
    }

    public function handle()
    {
        $org = $this->organisation->findByCustomerId(1234);
    }
}
为您创建正确的对象。要插入模拟对象而不是
组织
类,您可以在测试中执行以下操作:

$mock = \Mockery::spy(Organization::class)->makePartial();
$mock->shouldReceive('findByCustomerId')->once();
$this->app->instance(Organization::class, $mock);