【问题标题】:UnauthorizedException not caught with Laravel 5 / CodeceptionLaravel 5 / Codeception 未捕获 UnauthorizedException
【发布时间】:2016-10-19 19:41:36
【问题描述】:

我试图在我的功能测试中使用 Codeception 拦截 UnauthorizedException。好吧,实际上我的功能测试是由代码接收触发的 Laravel 测试。所以,我尝试了两种方法:

/** @test
 *
 * @expectedException UnauthorizedException
 */
public function test_exception()
{

    $this->visit("/associations/1/edit")

}

或者

 /** @test
 *
 */
public function test_exception()
{
   \PHPUnit_Framework_TestCase::setExpectedException(UnauthorizedException::class);
    $this->visit("/associations/1/edit")

}

在我的控制器中,我只是将其用于测试:

 throw new UnauthorizedException();

在这两种情况下,它只是说:

Failed asserting that exception of type "UnauthorizedException" is thrown.

一切似乎都很好,但似乎不起作用......知道为什么吗???

编辑:我在控制器中的编辑方法

public function edit($id)
{

    $association = Association::findOrFail($id);
    $federation = $association->federation;

    if (Auth::user()->cannot('edit', $association)) { // I have checked with dd() my test goes here.
        throw new UnauthorizedException();
    }

    $users = User::all();
    $federations = Federation::all();

    return view('associations.form', compact('association', 'users', 'federations', 'federation'));
}

【问题讨论】:

  • 尝试过命名空间? \Illuminate\Contracts\Validation\UnauthorizedException
  • 我使用:使用 Illuminate\Contracts\Validation\UnauthorizedException;不应该是一样的吗?
  • 是的,应该。你能发布完整的控制器方法吗
  • 哪一个????编辑还是更新?
  • 抛出异常的那个

标签: laravel exception phpunit codeception


【解决方案1】:

我终于从here得到了解决方案:

我猜,基本思想是捕获异常并将其发送到返回视图的处理程序。

所以,为了测试,你应该在 Handler.php 中包含条件:

public function render($request, Exception $e)
{
    if (App::environment() == 'testing') {
        throw $e;
    }
    // Your exception management...

现在抛出异常!

【讨论】:

    猜你喜欢
    • 2015-08-06
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    相关资源
    最近更新 更多