laravel怎么运行 laravel怎么读
使用expectsQuestion()处理确认操作;expectsOutput()验证输出,实现Laravel Laravel
Artisan命令中使用$this-gt;ask()或$this-gt;secret()),你可以通过依赖Symfony Console组件提供的输入模拟功能来实现。使用expectsQuestion()模拟输入用户
Laravel提供了简洁的测试辅助方法expectsQuestion(),用于模拟请求命令中的用户输入。您可以在测试中链式调用它来预设对问题的回答。
示例:测试一个用户需要输入的 Artisan 命令
假设你有一个命令UserCreateCommand: email?'); // 用户创建逻辑... $this-gt;info(quot;User {$name} ({$email}) created.quot;);}登录后复制
的测试回复可以这样写://tests/Feature/CreateUserCommandTest.phpuse Illuminate\Support\Facades\Artisan;use Tests\TestCase;class CreateUserCommandTest extends TestCase{ public function test_it_can_create_a_user_with_input() { $this-gt;artisan('user:create') -gt;expectsQuestion('用户名是什么?', 'John Doe') -gt;expectsQuestion('用户电子邮件是什么?', 'john@example.com') -gt;expectsOutput('用户 John Doe (john@example.com) created.') -gt;assertExitCode(0); $this-amp;gt;secret() $secret = $this-gt;secret('输入密码:');登录后复制
测试时:面试猫
AI面试助手,在线面试神器,助你轻松拿Offer 39 查看详情
$this-gt;artisan('user:create') -gt;expectsQuestion('输入密码:','secret123') -gt;doesntExpectOutput('secret123'); //确保密码没有被打印登录后复制
注意:虽然方法名是expectsQuestion(),但它也适用于secret(),因为简单都是问题helper。模拟确认操作(yes/no)
对于布尔型确认,使用expectsConfirmation():if ($this-gt;confirm('Do you Wish to continue?')) { //执行操作}登录后复制
测试:$this-gt;artisan('user:create') -gt;expectsConfirmation('Do you Wish to continue?', 'yes') -gt;assertExitCode(0);登录后复制多个输入和复杂流程
你可以连续调用expectsQuestion()来模拟多个输入步骤,Laravel 会按顺序匹配:$this-gt;artisan('setup:app') -gt;expectsQuestion('数据库主机?', 'localhost') -gt;expectsQuestion('数据库名称?', 'myapp') -gt;expectsQuestion('数据库密码?', 'pass') -gt;expectsOutput('数据库已配置');登录后复制
关键点总结:expectsQuestion('question', 'answer'):模拟一般输入expectsConfirmation('question', 'yes|no'):模拟是/否确认expectsOutput('text'):断言命令输出包含指定所有模拟内容基于Symfony Console的QuestionHelper,Laravel测试TestCase已封装好
基本上就这些。只需使用命令了交互方法(ask,secret,confirm),就可以通过上述方式在测真实的用户交互。
以上就是laravel怎么在命令行测试中模拟用户的输入_lara vel命令行测试用户输入常识网其他相关文章!相关标签: php word laravel cad app ai 邮箱 red symfony laravel 封装布尔型 console this PHP
