php – Laravel 5控制台(手工)命令单元测试
发布时间:2020-12-14 19:41:21 所属栏目:大数据 来源:网络整理
导读:我将Laravel 4.2应用程序迁移到5.1(从5.0开始),并且我的控制台命令单元测试很麻烦.我有工匠指令,我需要测试产生的控制台输出,正确的问题/响应处理和与其他服??务的交互(使用嘲笑).对于所有的优点,Laravel文档对于测试控制台命令而言是不幸的. 我终于找到了一
|
我将Laravel 4.2应用程序迁移到5.1(从5.0开始),并且我的控制台命令单元测试很麻烦.我有工匠指令,我需要测试产生的控制台输出,正确的问题/响应处理和与其他服??务的交互(使用嘲笑).对于所有的优点,Laravel文档对于测试控制台命令而言是不幸的.
我终于找到了一种创建这些测试的方法,但它感觉就像是使用setLaravel和setApplication调用的一个黑客. 有没有更好的方法来做到这一点?我希望我可以将我的模拟实例添加到Laravel IoC容器中,并让它创建用于测试所有正确设置的命令.恐怕我的单元测试会随着更新的Laravel版本而轻松破解. 这是我的单元测试: 使用陈述: use Mockery as m; use AppConsoleCommandsAddClientCommand; use SymfonyComponentConsoleTesterCommandTester; 建立 public function setUp() {
parent::setUp();
$this->store = m::mock('AppServicesStore');
$this->command = new AddClientCommand($this->store);
// Taken from laravel/framework artisan command unit tests
// (e.g. tests/Database/DatabaseMigrationRollbackCommandTest.php)
$this->command->setLaravel($this->app->make('IlluminateContractsFoundationApplication'));
// Required to provide input to command questions (provides command->getHelper())
// Taken from ??? when I first built my command tests in Laravel 4.2
$this->command->setApplication($this->app->make('SymfonyComponentConsoleApplication'));
}
输入作为命令参数提供.检查控制台输出 public function testReadCommandOutput() {
$commandTester = new CommandTester($this->command);
$result = $commandTester->execute([
'--client-name' => 'New Client',]);
$this->assertSame(0,$result);
$templatePath = $this->testTemplate;
// Check console output
$this->assertEquals(1,preg_match('/^Client 'New Client' was added./m',$commandTester->getDisplay()));
}
模拟键盘提供的输入 public function testAnswerQuestions() {
$commandTester = new CommandTester($this->command);
// Simulate keyboard input in console for new client
$inputs = $this->command->getHelper('question');
$inputs->setInputStream($this->getInputStream("New Clientn"));
$result = $commandTester->execute([]);
$this->assertSame(0,$commandTester->getDisplay()));
}
protected function getInputStream($input) {
$stream = fopen('php://memory','r+',false);
fputs($stream,$input);
rewind($stream);
return $stream;
}
更新 >这不适用于Laravel 5.1 #11946
我以前做过如下 – 我的控制台命令返回一个json响应:
public function getConsoleResponse()
{
$kernel = $this->app->make(IlluminateContractsConsoleKernel::class);
$status = $kernel->handle(
$input = new SymfonyComponentConsoleInputArrayInput([
'command' => 'test:command',// put your command name here
]),$output = new SymfonyComponentConsoleOutputBufferedOutput
);
return json_decode($output->fetch(),true);
}
所以如果你想把它放在它自己的命令测试器类,或者作为TestCase等中的一个功能,直到你. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
