首页 > 解决方案 > PHPUnit:测试 POST 请求

问题描述

我想测试 POST 请求。我的控制器的方法如下所示:

  public function store(Request $request)
  {
      $this->Validate($request, [
        'name' => 'required|string|min:5'
      ]);
      $product = Product::create([
        'name' => $request->name
      ]);
      return redirect()->back();
  }

所以,我写了这个简单的测试,但我有一个错误,因为它收到了 302 代码:

$response = $this->post('/product/store', [
          'name' => 'Hello'
        ])
        ->assertStatus(201);

我认为这个问题是因为我在存储数据后重定向页面。我如何测试这个 POST 请求?

标签: phplaravelphpunit

解决方案


对于重定向,您可以断言状态为 302 ( https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection )

$response = $this->post('/product/store', [
      'name' => 'Hello'
    ])
    ->assertStatus(302);

推荐阅读