【问题标题】:Laravel 5.8 Illuminate\Validation\ValidationException: The given data was invalidLaravel 5.8 Illuminate\Validation\ValidationException:给定的数据无效
【发布时间】:2020-04-16 11:19:09
【问题描述】:

我的控制器中有这样的存储方法

public function store()
{
     request()->validate(['family'=>'required']);
     User::create(request()->all());
     return redirect('/users');
}

和这样的测试方法

/** @test */
public function a_user_require_family()
{
    $this->withoutExceptionHandling();
    $this->post('/users', [])->assertSessionHasErrors('family');
}

它告诉我这个:

1) 测试\功能\用户测试::a_user_require_family
Illuminate\Validation\ValidationException:给定的数据无效。

【问题讨论】:

    标签: php laravel laravel-5 phpunit laravel-unit-test


    【解决方案1】:

    您不能使用$this->withoutExceptionHandling()->assertSessionHasErrors('family'),因为所有验证错误都是由您明确禁止运行的Illuminate\Validation\ValidationException 处理的异常。

    只需删除$this->withoutExceptionHandling(),您的测试就会通过。

    【讨论】:

    • 我评论了$this->withoutExceptionHandling();,但显示了同样的错误
    【解决方案2】:

    您正在使用 assertSessionHasErrors('family') ,它仅在密钥在请求正文中传递然后未通过验证时才会在密钥 family 上捕获 ValidationException

    但在您的情况下,您根本没有传递上述密钥(您发送一个空正文 [])。

    在这种情况下,您需要使用assertSessionMissing()

    试试:

    $this->post('/users', [])->assertSessionMissing('family');
    

    Laravel 文档https://laravel.com/docs/5.8/http-tests#assert-session-missing

    【讨论】:

      猜你喜欢
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-17
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      相关资源
      最近更新 更多