【问题标题】:PHPUnit: testing POST requestPHPUnit:测试 POST 请求
【发布时间】:2020-03-26 23:31:50
【问题描述】:

我想测试 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 请求?

【问题讨论】:

标签: php laravel phpunit


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 2013-02-12
    相关资源
    最近更新 更多