【问题标题】:unit test render an exception into an HTTP response?单元测试将异常呈现到 HTTP 响应中?
【发布时间】:2017-09-14 12:55:12
【问题描述】:

如何测试render() 是否是 HTTP 响应的异常工作正常。我想测试而不调用$this->get()

这是 Laravel 中的一个方法:

  public function render($request, Exception $e)
  {
        $response['exception'] = get_class($e);
        $response['message'] = $e->getMessage();

        if ($e instanceof LockException) {
            return $this->errorResponse('lock', $response, 'Lock error has occurred', $e->getCode());
        }

        return parent::render($request, $e);
    }

我需要测试LockException 是否已变成 HTTP 响应。

【问题讨论】:

    标签: php laravel phpunit laravel-5.4


    【解决方案1】:

    类似的东西。在您的测试中,将控制器实例化为一个变量,创建一个空白请求并传入您的 LockException:

    $response = $controller->render($request, $exception);
    $this->assertEquals('string of HTML you expect', $response);
    

    【讨论】:

    • 如何实例化 $controller ?从哪里声明的
    • 以同样的方式实例化任何对象! $controller = new Whatever($possiblyPassingSomethingItNeedsToo);
    • 哦,哈哈。我需要找到一种方法来模拟 \Illuminate\Http\Request 以传递到 render
    • 你不能创建一个新的吗?我们没有测试该功能,只是测试异常
    猜你喜欢
    • 2018-06-04
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 2013-02-21
    • 2017-02-16
    • 1970-01-01
    相关资源
    最近更新 更多