使用phpunit测试Laravel(5.1)控制台命令 [英] Testing Laravel (5.1) console commands with phpunit

查看:56
本文介绍了使用phpunit测试Laravel(5.1)控制台命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

测试Laravel控制台命令的最佳方法是什么?

What is the best way to test Laravel console commands?

这是我正在运行的命令的示例.它在构造函数和handle方法中接受一个值.

Here is an example of a command I'm running. It takes in a value in the constructor and in the handle method.

class DoSomething extends Command
{
    protected $signature = 'app:do-something';
    protected $description = 'Does something';

    public function __construct(A $a)
    {
        ...
    }

    public function handle(B $b)
    {
        ...    
    }
}

在测试类中,我可以模拟A和B,但是我不知道如何传入$ a.

In my test class, I can mock both A and B, but I can't figure out how to pass $a in.

$this->artisan('app:do-something', [$b]);

有可能吗?还是我要解决所有这些错误?我是否应该将所有事情都传递给handle()方法?

Is it possible? Or am I going about this all wrong? Should I pass everything in thought the handle() method?

谢谢.

推荐答案

您将不得不在测试中调用命令的方式进行更改,但是可以模拟通过的对象.

You will have to change around how you call the command in testing, but it is possible to mock an object passed through.

如果Artisan使用的类是像这样依赖注入的:

If the class used by Artisan is dependency-injected like this:

public function __construct(ActualObject $mocked_A)
{
    //
}

然后像这样编写测试用例:

Then write up the test case like this:

$mocked_A = Mockery::mock('ActualObject');
$this->app->instance('ActualObject', $mocked_A);

$kernel = $this->app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
    $input = new Symfony\Component\Console\Input\ArrayInput([
        'command' => 'app:do-something',
    ]),
    $output = new Symfony\Component\Console\Output\BufferedOutput
);
$console_output = $output->fetch();

$this->app->instance('ActualObject', $mocked_A);行中,您可以调用并使用类或对象的模拟版本,而不是实际版本.

The $this->app->instance('ActualObject', $mocked_A); line is where you are able to call upon and use the mocked version of your class, or object, instead of the actual.

这将在Laravel或Lumen中使用.

This will work in Laravel or Lumen.

这篇关于使用phpunit测试Laravel(5.1)控制台命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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