【发布时间】:2019-03-14 09:32:06
【问题描述】:
我有一个调用另一个类函数的工匠命令。此函数向另一台服务器发出 get 请求,我不希望在测试期间发生此 get 请求。
我通常的解决方案是使用 mockery 来模拟该函数,但这似乎不起作用。
为什么当我使用 Artisan::call('command::getFoo') 调用 artisan 命令时没有调用我的 mock?
命令类
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Foo;
class GetFoo extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'command:getFoo';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Get the foo data';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
return Foo::get(); // Returns true
}
}
测试类
namespace Tests\Feature;
use Tests\TestCase;
use App\Foo;
class FooCommandTest extends TestCase
{
public function testThatWeCanGetFoo()
{
$fooClass = Mockery::mock(Foo::class);
$fooClass->shouldReceive(['get' => false]); // Overwrite the foo class to return false instead of true
$fooData = \Artisan::call('command:getFoo');
$this->assertFalse($fooData);
}
}
当我运行测试时它失败了,因为它仍然恢复真实。这意味着没有调用嘲笑类。这里发生了什么?如何测试这个命令?
【问题讨论】:
-
Foo类静态引用你的真实世界依赖,这就是它不使用模拟对象的原因。您需要将其作为依赖项注入到您的工匠命令中。老实说,不确定如何在命令上实现这一点,但可以肯定的是,快速的谷歌可能会显示出方法。 -
好的,谢谢。这让我找到了解决方案。
-
很高兴知道,请随时发布答案,以便其他人学习。我也很好奇。问候!
标签: php laravel phpunit mockery