Vin*_*raz 8 php laravel laravel-testing laravel-artisan
我正在为 Laravel Artisan 控制台命令编写一个非常基本的测试,如下所示:
$this->artisan("my-command", ["--some-option" => "some-value"])
->expectsOutput("the expected output");
Run Code Online (Sandbox Code Playgroud)
测试没有通过。我真的很麻烦,因为“预期输出”正是手动执行时命令输出的内容。
但没关系,我只需要检查通过自动化测试执行时命令输出的实际情况,对吧?但是等等,我该怎么做呢?
我尝试了以下方法:
$output = new BufferedConsoleOutput();
Artisan::call("my-command", ["--some-option", "some-value"], $output);
// dd($output->fetch()
$this->assertTrue($output->fetch() === "the expected output");
Run Code Online (Sandbox Code Playgroud)
但 $output->fetch() 似乎总是空的。
简而言之:如何在测试上下文中打印 Laravel 命令的实际输出?
mik*_*n32 20
如果您阻止 Laravel 模拟控制台输出,则可以捕获它以进行检查。
假设您的测试失败:
public function testStuffDoesntBreak(): void
{
$this->artisan("my-command", ["--some-option" => "some-value"])
->expectsOutput("the expected output");
}
Run Code Online (Sandbox Code Playgroud)
您可以将其重写为:
use Illuminate\Support\Facades\Artisan;
...
public function testStuffDoesntBreak(): void
{
$this->withoutMockingConsoleOutput()
->artisan("my-command", ["--some-option" => "some-value"]);
// capture the text output from the command
$result = Artisan::output();
// use standard text assertions
$this->assertEquals("the expected output", $result);
}
Run Code Online (Sandbox Code Playgroud)
当您禁用控制台模拟时,该artisan()方法将不再流畅,而是返回命令的退出代码。但它确实允许Artisan外观访问其输出。
无论您是想重写测试以始终模拟输出,还是在尝试调试错误时即时更改它们,都取决于个人喜好。我已经完成了后者,因为我不想错过像expectsTable().
| 归档时间: |
|
| 查看次数: |
3619 次 |
| 最近记录: |