【问题标题】:Skip Laravel's FormRequest Validation跳过 Laravel 的 FormRequest 验证
【发布时间】:2019-12-14 05:06:36
【问题描述】:

我最近将HaveIBeenPwned 添加到我的表单请求类中以检查破解密码。鉴于这会进行外部 API 调用,有没有办法让我在测试期间完全跳过此验证规则或 FormRequest 类?

这是我在测试中提出的要求。

    $params = [
        'first_name' => $this->faker->firstName(),
        'last_name' => $this->faker->lastName(),
        'email' => $email,
        'password' => '$password',
        'password_confirmation' => '$password',
        'terms' => true,
        'invitation' => $invitation->token
    ];


    $response = $this->json('POST', '/register-invited', $params);

我正在测试的功能驻留在控制器上。在我的测试中,我发布了一个通过 FormRequest 的数据数组,其规则如下。

 public function rules()
 {
 return [
  'first_name' => 'required|string|max:70',
  'last_name' => 'required|string|max:70',
  'email' => 
  'required|email|unique:users,email|max:255|exists:invitations,email',
  'password' => 'required|string|min:8|pwned|confirmed',
   'is_trial_user' => 'nullable|boolean',
   'terms' => 'required|boolean|accepted',
    ];
  }

我想覆盖密码上的“pwned”规则,这样我就可以直接访问控制器,而不必担心通过验证。

【问题讨论】:

  • laravel.com/docs/5.8/mocking。这可能需要一点点挖掘,但模拟您的验证器正在进行的特定 API 调用将意味着您仍然可以对 FormRequest 使用自动化测试。
  • 我已经读过了,我不确定从哪里开始。值得注意的是,我是比较新的 Laravel。
  • 也许this post 会帮助您入门?如果您无法弄清楚,我可以建议发布有问题的验证代码以及调用它的上下文吗?
  • @PtrTon 我已经更新了我的问题以添加更多上下文。

标签: laravel phpunit


【解决方案1】:

根据提供的信息,我会说您正在执行一个执行实际 Web 请求的集成测试。在这种情况下,我认为您的测试套件可以连接到第三方,因为这是“集成”的一部分。

如果您仍然喜欢模拟验证规则,您可以使用swap out the Validator 使用swap

$mock = Mockery::mock(Validator::class);
$mock->shouldReceive('some-method')->andReturn('some-result');
Validator::swap($mock);

或者通过在服务容器中替换它的实例

$mock = Mockery::mock(Validator::class);
$mock->shouldReceive('some-method')->andReturn('some-result');
App:bind($mock);

或者,您可以模拟 Cache::remember() 调用,它是Pwned validation rule itself 的内部部分。这会导致类似

Cache::shouldReceive('remember')
   ->once()
   ->andReturn(new \Illuminate\Support\Collection([]));

【讨论】:

  • 哇哦!做到了。非常感谢您的帮助!
  • 我能够让Cache 选项起作用,但对于第一个建议,我对输入感到困惑。我实际上是使用Validator 类,还是使用Pwned 类?
  • 不幸的是Validator::swapApp:bind 方法只支持替换整个Validator 类,所以你必须模拟对它的每个调用。据我所知,Pwned 类无法被模拟,因为只能模拟服务容器中的 Laravel 外观和服务。
猜你喜欢
  • 2020-06-25
  • 2017-02-03
  • 2015-10-04
  • 2018-06-04
  • 1970-01-01
  • 1970-01-01
  • 2018-02-18
  • 2020-01-05
  • 2020-06-28
相关资源
最近更新 更多