【发布时间】:2019-11-13 03:34:30
【问题描述】:
我想测试我的 Laravel Artisan 命令。所以我需要模拟一个对象并存根这个模拟的对象方法。在我的测试中,我无法使用真正的 SFTP 环境。
这是我的命令的handle():
public function handle()
{
$sftp = new SFTP('my.sftpenv.com');
$sftp->login('foo', 'bar');
}
我想在我的测试中模拟 SFTP:
$sftp = $this->createMock(SFTP::class);
$sftp->expects($this->any())->method('login')->with('foo', 'bar');
$this->artisan('import:foo');
在Cannot connect to ...:22 中运行测试结果,它来自SFTP 的原始login 方法。所以mock/stub没有生效。
所以我的问题是:如何在 Laravel Artisan 命令测试中模拟对象?
【问题讨论】:
-
您可以在容器中注入模拟对象。在此行之前:
$this->artisan('import:foo'); -
你能举个例子吗?
-
顺便说一句:
$this->app->bind(SFTP::class, $sftp);
标签: laravel unit-testing command laravel-artisan