Laravel单元测试 - 根据测试方法更改配置值

Vin*_*rat 11 php phpunit unit-testing laravel

我有一个用于验证帐户的系统的应用程序(注册 - >获取带有激活链接的电子邮件 - >已验证帐户).该验证流程是可选的,可以使用配置值关闭:

// config/auth.php
return [
  // ...
  'enable_verification' => true
];
Run Code Online (Sandbox Code Playgroud)

我想测试注册控制器:

  • 它应该在两种情况下都重定向到主页
  • 验证开启时,主页应显示"已发送电子邮件"消息
  • 验证关闭时,主页应显示"已创建帐户"消息
  • 等等

我的测试方法:

public function test_UserProperlyCreated_WithVerificationDisabled()
{
    $this->app['config']->set('auth.verification.enabled', false);

    $this
        ->visit(route('frontend.auth.register.form'))
        ->type('Test', 'name')
        ->type('test@example.com', 'email')
        ->type('123123', 'password')
        ->type('123123', 'password_confirmation')
        ->press('Register');

    $this
        ->seePageIs('/')
        ->see(trans('auth.registration.complete'));
}

public function test_UserProperlyCreated_WithVerificationEnabled()
{
    $this->app['config']->set('auth.verification.enabled', true);

    $this
        ->visit(route('frontend.auth.register.form'))
        ->type('Test', 'name')
        ->type('test@example.com', 'email')
        ->type('123123', 'password')
        ->type('123123', 'password_confirmation')
        ->press('Register');

    $this
        ->seePageIs('/')
        ->see(trans('auth.registration.needs_verification'));
}
Run Code Online (Sandbox Code Playgroud)

在调试时,我注意到在控制器方法内部的配置值总是设置为配置文件中的值,无论我用什么设置我的 $this->app['config']->set...

我对用户存储库本身进行了其他测试,以检查在验证为ON或OFF时它是否都有效.测试的行为符合预期.

知道为什么控制器失败以及如何解决这个问题?

Ale*_*not 10

如果我理解你的问题 - 你正在寻找"如何设置配置参数",那么你可以使用 Config::set($key, $value)

  • 如果您对助手感觉更舒服或使用流明,您也可以执行`config() - > set($ key,$ value) (6认同)
  • 如果你使用 `Config::set($key, $value)`,那么你需要导入 `Illuminate\Support\Facades\Config`,但这在 Lumen 中仍然有效,@suarsenegger 的回答也是如此。 (2认同)

小智 6

正确答案在上面

Config::set($key, $value) 
Run Code Online (Sandbox Code Playgroud)

例子

//Not forget to add namespace using class.
use Config;

//Example to set config. (configFile.key)
Config::set('auth.enable_verification', false); 
Run Code Online (Sandbox Code Playgroud)