Published in
4 min readDec 29, 2020
# 版本
# 前言
我喜歡使用 Laravel 開發的感覺, 除了開發快速, 程式碼簡潔且優雅之外, Laravel 框架本身也是一個很好的學習參照物。 本篇主要將官方文件重點整理成 Q&A 的形式呈現, 原子化的概念, 這方式並不適用於每個人, 但若對你有幫助, 我會很開心。
Input / Output Expectations
以下的 Laravel Console Testing example code 的意思是?
- Example:
<?php
// command
Artisan::command('question', function () {
$name = $this->ask('What is your name?');
$language = $this->choice('Which language do you prefer?', [
'PHP',
'Ruby',
'Python',
]);
$this->line('Your name is '.$name.' and you prefer '.$language.'.');
});
// testing method
public function testConsoleCommand()
{
$this->artisan('question')
->expectsQuestion('What is your name?', 'Taylor Otwell')
->expectsQuestion('Which language do you prefer?', 'PHP')
->expectsOutput('Your name is Taylor Otwell and you prefer PHP.')
->doesntExpectOutput('Your name is Taylor Otwell and you prefer Ruby.')
->assertExitCode(0);
}
- Answer:
artisan
: 指定要斷言的 command nameexpectsQuestion
: 定義要斷言的 key (questions), 以及 value (answers)expectsOutput
: 斷言會有 line, error, info 等 method 的輸出doesntExpectOutput
: 斷言不可有的 line, error, info 等 method 的輸出assertExitCode
: 斷言 exit code, 即$$
為 0
# Confirmation Expectations
以下的 Laravel Console Testing example code 的意思是?
- Example:
<?php
$this->artisan('module:import')
->expectsConfirmation('Do you really wish to run this command?', 'no')
->assertExitCode(1);
- Answer: 斷言 command confirmation 以及其輸出
# Table Expectations
以下的 Laravel Console Testing example code 的意思是?
- Example:
<?php
$this->artisan('users:all')
->expectsTable([
'ID',
'Email',
], [
[1, 'taylor@example.com'],
[2, 'abigail@example.com'],
]);
- Answer: 斷言 command 為
'users:all'
, arg1 為 table header, arg2 為 table data