Laravel资源控制器的PHPUnit测试异常 [英] PHPUnit Testing Exceptions for Laravel Resource Controllers

查看:617
本文介绍了Laravel资源控制器的PHPUnit测试异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以用Laravel资源控制器测试异常吗?每次我尝试执行以下操作:

Is it possible to test Exceptions with Laravel resource controllers? Every time I try to do the following:

/**
 * @expectedException Exception
 * @expectedExceptionMessage Just testing this out
 */
public function testMyPost() {
    $response = $this->call('POST', '/api/myapi/', array('testing' => 1));
}

我得到:

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

我已尝试过这个与 \Exception 异常

I've tried this with \Exception and Exception.

在我的资源控制器中我有:

In my resource controller I have:

public function store() {
    throw new \Exception('Just for testing!');
}



<我也试过使用:

Does anyone has any idea of I can test Exceptions? I've also tried using:

    $this->setExpectedException('InvalidArgumentException');


推荐答案

问题是hannesvdvreken状态;异常被捕获。一个简单的解决方法是告诉Laravels的错误/异常处理程序,当我们测试时,我们只是想抛出我们的异常。

The problem is as hannesvdvreken states; the exception is caught. An easy work-around is to tell Laravels errort/exception handler, that when we are testing, we just want our exceptions thrown.

可能看起来像这样: / p>

That could look something like this:

    // If we are testing, just throw the exception.
    if (App::environment() == 'testing') {
        throw $e;
    }

对于Laravel 5,这应该在应用程序/异常/ Handler.php

For Laravel 5, this should go in the render method in app/Exceptions/Handler.php

对于Laravel 4,这应该在app / start / global.php中:

For Laravel 4, this should go in app/start/global.php within:

App::error(function(Exception $exception, $code)...

这篇关于Laravel资源控制器的PHPUnit测试异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆