Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel测试| Laravel Artisan命令中的模拟对象_Laravel_Unit Testing_Command_Laravel Artisan - Fatal编程技术网

Laravel测试| Laravel Artisan命令中的模拟对象

Laravel测试| Laravel Artisan命令中的模拟对象,laravel,unit-testing,command,laravel-artisan,Laravel,Unit Testing,Command,Laravel Artisan,我想测试我的Laravel Artisan命令。所以我需要模拟一个对象,并将这个模拟对象方法存根。在我的测试中,我无法使用真正的SFTP环境 这是我的命令的handle(): public function handle() { $sftp = new SFTP('my.sftpenv.com'); $sftp->login('foo', 'bar'); } 我想在测试中模拟SFTP: $sftp = $this->createMock(SFTP::class); $s

我想测试我的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');
中运行测试结果无法连接到…:22
,它来自
SFTP
的原始
login
方法。因此,模拟/存根不会生效


因此,我的问题是:如何在Laravel Artisan命令测试中模拟对象?

我认为@Mesuti的意思是,如果将
SFTP
对象添加到服务容器中,则在运行测试时可以将其与模拟对象交换

您可以这样绑定它(在
app/Providers/AppServiceProvider.php中或在新的服务提供商中):

然后,您可以在命令的处理程序中创建对象(例如,
$sftp=resolve('sftp');
),然后在测试中创建对象,如下所示:

$this->mock(SFTP::class, function ($mock) {
    $mock->expects()->login('foo', 'bar')->andReturn('whatever you want it to return');
});

请注意,您正在模拟的服务应该在命令的
handle
方法中解决,而不是像在其他情况下那样在
\u construct
方法中解决。看起来artisan命令是在测试运行之前解析的,因此如果在命令的构造函数中解析服务,它将不会解析为模拟实例

您可以在容器中注入模拟对象。在这一行之前:
$this->artisan('import:foo')
你能提供一个例子吗?它可以这样做:
$this->app->bind(SFTP::class,$SFTP)
$this->mock(SFTP::class, function ($mock) {
    $mock->expects()->login('foo', 'bar')->andReturn('whatever you want it to return');
});