Laravel测试| Laravel Artisan Command中的模拟对象 [英] Laravel Test | Mock object in Laravel Artisan Command

查看:142
本文介绍了Laravel测试| Laravel Artisan Command中的模拟对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试我的Laravel Artisan命令.因此,我需要模拟一个对象并对该模拟对象的方法进行存根.在测试中,我无法使用真实的SFTP环境.

I want to test my Laravel Artisan command. So I need to mock an object and stubs this mocked object methods. In my test, I cannot use the real SFTP environment.

这是我命令的handle():

public function handle()
{
   $sftp = new SFTP('my.sftpenv.com');
   $sftp->login('foo', 'bar');
}

我想在测试中模拟SFTP:

I want to mock the SFTP in my test:

$sftp = $this->createMock(SFTP::class);
$sftp->expects($this->any())->method('login')->with('foo', 'bar');
$this->artisan('import:foo');

Cannot connect to ...:22中运行测试结果,该结果来自SFTP的原始login方法.因此模拟/存根不会生效.

Running the test results in a Cannot connect to ...:22, which comes from the original login method of SFTP. So the mock/stub does not take effect.

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

So my question is: how can I mock an object in a Laravel Artisan command test?

推荐答案

我认为@Mesuti的意思是,如果您将您的SFTP对象绑定到您的服务容器,您可以在运行测试时将其与模拟对象交换出去.

I think what @Mesuti means is that if you bind your SFTP object to your service container you would be able to swap it out with a mock object when running your test.

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

You could bind it like this (either inside your app/Providers/AppServiceProvider.php or a new service provider):

$this->app->singleton(SFTP::class, function ($app) {
            return new SFTP('my.sftpenv.com');
        });

然后您可以解析命令处理程序中的对象(例如$sftp = resolve('SFTP'); ),然后将其模拟在您的测试中:

You could then resolve the object in your command's handler (e.g. $sftp = resolve('SFTP');) and then mock it inside your test like this:

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

仅供以后的读者注意,您要嘲笑的服务应在命令的handle方法中解决,而不是像在其他情况下通常会在的__construct方法中解决.看来artisan命令在运行测试之前已解决,因此,如果您在命令的构造函数中解析服务,则不会解析为模拟实例.

Just a note for future readers that service you are mocking should be resolved in the handle method of the command and not in the __construct method like you would often do in other circumstances. It seems like the artisan commands are resolved before the tests are run so if you resolve the service in the constructor of the command, it wouldn't resolve to the mocked instance.

这篇关于Laravel测试| Laravel Artisan Command中的模拟对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆