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

查看:34
本文介绍了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.

我已经尝试过使用 ExceptionException.

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所说;异常被捕获.一个简单的解决方法是告诉 Laravel 错误/异常处理程序,当我们测试时,我们只想抛出我们的异常.

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.

可能看起来像这样:

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

对于 Laravel 5,这应该放在 app/Exceptions/Handler.php 的 render 方法中

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天全站免登陆