【问题标题】:Illuminate\Validation\ValidationException : The given data was invalid. Called when trying to get the json from a response while testingIlluminate\Validation\ValidationException :给定的数据无效。在测试时尝试从响应中获取 json 时调用
【发布时间】:2019-04-06 22:24:14
【问题描述】:

我有以下测试:

public function testStoreMemberValidation()
{
    $response = $this->withExceptionHandling()->post('/api/members', [
        "name" => "Eve",
        "age" => "invalid"
    ], ['X-Requested-With' => 'XMLHttpRequest']);

    dd($response->json());
};

我试图断言响应是验证错误的形式。控制器方法如下:

public function store(Request $request)
{
    $data = $request->validate([
        'name' => 'required|string',
        'age' => 'required|integer',
    ]);

    Member::create($data);
}

但是,每当我调用任何调用 $response->json()(其中大多数)的断言时,我都会遇到异常:

Illuminate\Validation\ValidationException : 给定的数据无效。

如何在不引发此错误的情况下对此响应执行断言?

注意,我使用的是 Laravel 5.7。

【问题讨论】:

  • Laravel 默认情况下会这样做,所以看起来你已经添加了$this->withoutExceptionHandling
  • 另外,您可以使用$this->postJson() 来避免手动添加X-Requested-With 标头,并且您可以使用$response->assertJsonValidationErrors('field_name') 测试验证错误。
  • 感谢@MartinBean,将其更改为$this->postJson() 似乎已修复它。我很确定我没有在任何地方打电话给$this->withoutExceptionHandling()

标签: laravel laravel-validation laravel-testing


【解决方案1】:

您的测试中有withExceptionHandling(),将其删除,它应该可以工作。

$response = $this->withExceptionHandling()->post('/api/members', [
        "name" => "Eve",
        "age" => "invalid"
    ], ['X-Requested-With' => 'XMLHttpRequest']);

应该是

$response = $this->post('/api/members', [
            "name" => "Eve",
            "age" => "invalid"
        ], ['X-Requested-With' => 'XMLHttpRequest']);

【讨论】:

  • 也遇到了同样的问题。删除 withExceptionHandling 会清除错误。这样做有风险吗?我觉得无论哪种方式测试都应该通过。
猜你喜欢
  • 2020-04-16
  • 2019-09-19
  • 2019-11-19
  • 2018-09-11
  • 2021-06-17
  • 1970-01-01
  • 2020-07-11
  • 2020-05-11
  • 1970-01-01
相关资源
最近更新 更多