使用 expectsQuestion() 模拟用户输入,如 ask 和 secret;expectsConfirmation() 处理确认操作;expectsOutput() 验证输出,实现 Laravel 命令行测试中交互式输入的自动化验证。

在 Laravel 的命令行测试中,如果你想模拟用户输入(例如在 Artisan 命令中使用 $this->ask() 或 $this->secret()),你可以通过依赖 Symfony Console 组件提供的 输入模拟功能 来实现。
Laravel 提供了简洁的测试辅助方法 expectsQuestion(),用于模拟交互式命令中的用户输入。你可以在测试中链式调用它来预设对问题的回答。
示例:测试一个需要用户输入的 Artisan 命令
假设你有一个命令 UserCreateCommand,它会询问用户名和邮箱:
// app/Console/Commands/UserCreateCommand.php
public function handle()
{
    $name = $this->ask('What is the user name?');
    $email = $this->ask('What is the user email?');
    // 创建用户逻辑...
    $this->info("User {$name} ({$email}) created.");
}对应的测试可以这样写:
// tests/Feature/CreateUserCommandTest.php
use Illuminate\Support\Facades\Artisan;
use Tests\TestCase;
class CreateUserCommandTest extends TestCase
{
    public function test_it_can_create_a_user_with_input()
    {
        $this->artisan('user:create')
             ->expectsQuestion('What is the user name?', 'John Doe')
             ->expectsQuestion('What is the user email?', 'john@example.com')
             ->expectsOutput('User John Doe (john@example.com) created.')
             ->assertExitCode(0);
    }
}如果你使用的是 $this->secret() 方法(输入不回显),可以使用 expectsQuestion() 一样处理,但建议明确说明是 secret 类型:
$secret = $this->secret('Enter password:');测试时:
$this->artisan('user:create')
     ->expectsQuestion('Enter password:', 'secret123')
     ->doesntExpectOutput('secret123'); // 确保密码没被打印注意:虽然方法名是 expectsQuestion(),但它也适用于 secret(),因为底层都是 question helper。
对于布尔型确认,使用 expectsConfirmation():
if ($this->confirm('Do you wish to continue?')) {
    // 执行操作
}测试:
$this->artisan('user:create')
     ->expectsConfirmation('Do you wish to continue?', 'yes')
     ->assertExitCode(0);你可以连续调用 expectsQuestion() 来模拟多个输入步骤,Laravel 会按顺序匹配:
$this->artisan('setup:app')
     ->expectsQuestion('Database host?', 'localhost')
     ->expectsQuestion('Database name?', 'myapp')
     ->expectsQuestion('Database password?', 'pass')
     ->expectsOutput('Database configured successfully.');关键点总结:
expectsQuestion('question', 'answer'):模拟一般输入expectsConfirmation('question', 'yes|no'):模拟 yes/no 确认expectsOutput('text'):断言命令输出包含指定内容QuestionHelper,Laravel 测试 TestCase 已封装好基本上就这些。只要命令使用了交互方法(ask, secret, confirm),就可以通过上述方式在测试中模拟输入,无需手动输入或依赖真实用户交互。
以上就是laravel怎么在命令行测试中模拟用户的输入_laravel命令行测试用户输入模拟方法的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号