【问题标题】:Testing/Mocking Custom Console commands测试/模拟自定义控制台命令
【发布时间】:2015-09-10 13:33:26
【问题描述】:

我构建了自己想要测试的简单命令。

基本上是这样的:

    <?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class NeatCommand extends Command
{


    protected $signature = 'my:neat:command {input_file : path for a json-formatted file to analyze}';

    protected $description = 'analyze an array of values';

    public function __construct()
    {
        parent::__construct();

    }


    public function handle()
    {

        $inputFile=$this->argument('input_file');
        echo $inputFile;
    }



}

所以我写了这个简单的测试:

/**
 * @test
 * @group neat
 */
public function commandShowsHelloWorld()
{

    $defaultCommand=Artisan::call('my:neat:command');

}

我只是想在这个阶段进行测试:缺少参数。但是当我现在运行它时,phpunit 将其作为错误:

There was 1 error:

1) App\Console\Commands\NeatCommandTest::commandShowsHelloWorld
RuntimeException: Not enough arguments.

所以我的问题是。我怎么能嘲笑整个事情......或者说像$this-&gt;shouldReturn('RuntimeException: Not enough arguments.');这样的话?

【问题讨论】:

  • 我想知道为什么你的测试函数不以'test'开头,为什么不使用phpunit phpunit.de/manual/current/en/…中的@expectedException注解
  • 是的,我得到了它与expectedExeption一起使用。谢谢。还有@test 在那里,忘了写在这里。
  • 您要测试什么?如果您尝试测试进行分析的代码,我会将其移至单独的库并使用标准单元测试方法对其进行测试。至于测试Artisan::call(...) - 我不会打扰。框架的东西(如何调用命令等)已经过测试;没有测试的是你写的自定义代码。
  • 我只是想测试它是否达到了预期。但是这个例子是微不足道的。添加更多选项后,我将不得不测试它带来的结果。我正在尝试从输入文件中生成字符串。

标签: php laravel laravel-5 phpunit laravel-5.1


【解决方案1】:

让它工作,但添加预期异常的@annotation。

/**
 * @test
 * @group neat
 * @expectedException RuntimeException
 * @expectedExceptionMessage Not enough arguments.
 */
public function commandWithoutArgumentsCausesError()
{

    $defaultCommand=Artisan::call('my:neat:command');

}

【讨论】:

    猜你喜欢
    • 2018-04-15
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 2016-11-28
    相关资源
    最近更新 更多