简体   繁体   English

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

[英]Laravel unit tests - changing a config value depending on test method

I have an application with a system to verify accounts (register -> get email with link to activate -> account verified).我有一个带有系统验证帐户的应用程序(注册 -> 获取带有激活链接的电子邮件 -> 帐户已验证)。 That verification flow is optional and can be switched off with a configuration value:该验证流程是可选的,可以使用配置值关闭:

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

I want to test the registration controller:我想测试注册控制器:

  • it should redirect to home page in both cases在这两种情况下它都应该重定向到主页
  • when verification is ON, home page should show message 'email sent'当验证打开时,主页应显示消息“已发送电子邮件”
  • when verification is OFF, home page should show message 'account created'当验证关闭时,主页应显示消息“帐户已创建”
  • etc.等。

My test methods:我的测试方法:

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

When debugging, I noticed that the configuration value when inside the controller method is always set to the value in the config file, no matter what I set with my $this->app['config']->set...调试时,我注意到控制器方法内部的配置值始终设置为配置文件中的值,无论我用$this->app['config']->set...

I have other tests on the user repository itself to check that it works both when validation is ON or OFF.我对用户存储库本身进行了其他测试,以检查它在验证打开或关闭时是否有效。 And there the tests behave as expected.在那里,测试按预期运行。

Any idea why it fails for controllers and how to fix that?知道为什么控制器失败以及如何解决这个问题吗?

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

Correct answer is above正确答案在上面

Config::set($key, $value) 

Example示例

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

//Example to set config. (configFile.key)
Config::set('auth.enable_verification', false); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM