【问题标题】:Laravel & phpunit set expected http error codeLaravel & phpunit 设置预期的 http 错误代码
【发布时间】:2017-02-04 14:01:25
【问题描述】:

我正在编写一些测试。这是我的测试:

  /** @test */
  public function a_normal_user_cannot_access_the_admin_panel()
  {
    // Note: This is a regular user, not an admin
    $user = factory(User::class)->create();
    $this->actingAs($user);
    $this->visit('/admin');

    // ????
  }

在我的MustBeAdministrator.php 中间件中:

  public function handle($request, Closure $next)
  {
      $user = $request->user();

      if ($user && $user->isAdmin) {
        return $next($request);
      }

      abort(403);
  }

当我访问 /admin 时,中间件中止并出现 403 错误。我如何用 phpunit 断言抛出了 http 错误?我知道$this->setExpectedException(),但我无法让它与 http 错误一起工作。我做错了吗?

注意:我对 phpunit 非常陌生,也有例外,如果这是一个愚蠢的问题,我很抱歉。如果您需要任何其他文件,这里是repo for this project,或者您可以直接询问。

【问题讨论】:

  • 嘿,你可以发布自己问题的答案,不被禁止:)
  • @iScrE4m 我确实回答了它,但我不会让我在 2 天内接受它作为答案:( 我会接受它。
  • 哦,抱歉,我没有注意到,所以没有在评论中显示:)

标签: php laravel laravel-5 phpunit tdd


【解决方案1】:
$user = factory(User::class)->create();
$this->actingAs($user);
$this->setExpectedException('Symfony\Component\HttpKernel\Exception\HttpException');
$this->get('/admin');
throw $this->response->exception;

Found this article。添加setExpectedException 行、throw 行并将visit 更改为get 似乎解决了我的问题

【讨论】:

  • @MihkelAllorg SO 不会让我再接受 2 个小时。那我会的。
【解决方案2】:

如果你想得到完整的响应对象,你可以使用call方法

/** @test */
public function a_normal_user_cannot_access_the_admin_panel()
{
  // Note: This is a regular user, not an admin
  $user = factory(User::class)->create();
  $this->actingAs($user);
  $response = $this->call('GET', '/admin');

  $this->assert(403, $response->status());
}

【讨论】:

    猜你喜欢
    • 2014-08-09
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 2018-03-01
    • 2015-09-16
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多