【问题标题】:How to cover exception in code coverage report Laravel 8?如何在代码覆盖率报告 Laravel 8 中覆盖异常?
【发布时间】:2021-09-27 16:10:00
【问题描述】:

我如何catch 任何异常来涵盖 100% 代码覆盖率报告?这仅涵盖代码中的try 条件。

控制器

public function getItem()
{
    try {
        // Some code
        return $result;
    } catch (Exception $e) {
        Log::error($e->getMessage());
        throw new Exception ("$e->getMessage ()", 500);
    }
}

测试文件

public function testGetItem() 
{
    $this->get('api/getitem')->assertStatus(200);
}

【问题讨论】:

  • 我知道这是示例代码,可能不是您实际在做的事情,但是尝试捕获并记录异常并抛出类似的异常只是不好的做法。如果你想测试 catch 块,你的测试用例需要做一些在你的代码中触发异常的事情。
  • 您需要修改您的请求,以免出错。我想没有真正的代码就没有真正的答案

标签: php laravel api testing laravel-8


【解决方案1】:

在 PHPUnit 中测试异常很容易,但由于它处理异常的方式,在 Laravel 中并不能像您期望的那样工作。

要在 Laravel 中测试异常,您首先需要禁用 Laravel 异常处理 - 如果您扩展提供的 TestCase,则可以使用 withoutExceptionHandling() 方法。

从那里您可以使用 PHPUnit 的 expectException() 方法。这是一个小例子。

use Tests\TestCase;

class ExceptionTest extends TestCase
{
    public function testExceptionIsThrownOnFailedRequest()
    {
        // Disable exception handling for the test.
        $this->withoutExceptionHandling();

        // Expect a specific exception class.
        $this->expectException(\Exception::class);

        // Expect a specific exception message.
        $this->expectExceptionMessage('Simulate a throw.');

        // Expect a specific exception code.
        $this->expectExceptionCode(0);

        // Code that triggers the exception.
        $this->get('/stackoverflow');
    }
}

现在,当测试运行时,它将禁用 Laravel 对此测试运行的异常处理,然后我们对应该发生的事情设置一些期望,最后,我们调用将满足这些期望的代码,在这种情况下,就是get() 调用路由。

现在如何满足期望将取决于您的应用程序。

【讨论】:

    猜你喜欢
    • 2011-03-18
    • 2021-06-26
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2019-04-24
    相关资源
    最近更新 更多