【问题标题】:Laravel unit tests - changing a config value depending on test methodLaravel 单元测试 - 根据测试方法更改配置值
【发布时间】:2016-10-18 03:51:34
【问题描述】:

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

// config/auth.php
return [
  // ...
  'enable_verification' => true
];

我要测试注册控制器:

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

我的测试方法:

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'));
}

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

我对用户存储库本身进行了其他测试,以检查它在验证打开或关闭时是否都有效。那里的测试按预期运行。

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

【问题讨论】:

    标签: php unit-testing laravel phpunit


    【解决方案1】:

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

    【讨论】:

    • 如果你觉得有助手更舒服或者你正在使用 Lumen,你也可以这样做config()->set($key, $value)
    • 如果您使用Config::set($key, $value),那么您需要导入Illuminate\Support\Facades\Config,但这仍然适用于Lumen,就像@suarsenegger 的回答一样。
    • 我相信这在 Laravel 的更高版本(8+)中被删除了,使得配置不可变,所以这种方法可能不会继续被支持。
    【解决方案2】:

    正确答案在上面

    Config::set($key, $value) 
    

    例子

    //Not forget to add namespace using class.
    use Config;
    
    //Example to set config. (configFile.key)
    Config::set('auth.enable_verification', false); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-01
      • 1970-01-01
      • 2021-12-15
      相关资源
      最近更新 更多