PHPUnit Laravel:如何单元测试自定义异常处理程序?

时间:2017-10-27 08:58:37

标签: php unit-testing laravel-5.4

我尝试对自定义异常处理程序类(位于app / Exceptions / Handler.php中)进行单元测试,但我不知道该怎么做...

我不知道如何使用模拟请求引发异常。

有人可以帮助我吗?

这是“渲染”方法:

/**
 * @param \Illuminate\Http\Request $request
 * @param Exception $e
 * @return \Illuminate\Http\RedirectResponse|\Symfony\Component\HttpFoundation\Response
 */
public function render($request, Exception $e)
{
    // This will replace our 404 response with
    // a JSON response.
    if ($e instanceof ModelNotFoundException &&
        $request->wantsJson()) {
        Log::error('render ModelNotFoundException');
        return response()->json([
            'error' => 'Resource not found'
        ], 404);
    }
    if ($e instanceof TokenMismatchException) {
        Log::error('render TokenMismatchException');
        return new RedirectResponse('login');
    }
    if ($e instanceof QueryException) {
        Log::error('render QueryException', ['exception' => $e]);
        return response()->view('errors.500', ['exception' => $e, 'QueryException' => true],500);
    }

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

这是我的测试用例:

/**
 * @test
 */
public function renderTokenMismatchException()
{
    $request = $this->createMock(Request::class);
    $request->expects($this->once())->willThrowException(new TokenMismatchException);
    $instance = new Handler($this->createMock(Application::class));
    $class    = new \ReflectionClass(Handler::class);
    $method   = $class->getMethod('render');
    $method->setAccessible(true);
    $expectedInstance = Response::class;
    $this->assertInstanceOf($expectedInstance, $method->invokeArgs($instance, [$request, $this->createMock(Exception::class)]));
}

2 个答案:

答案 0 :(得分:2)

我是怎么做到的:

/**
 * @test
 */
public function renderTokenMismatch()
{
    $request = $this->createMock(Request::class);
    $instance = new Handler($this->createMock(Container::class));
    $class    = new \ReflectionClass(Handler::class);
    $method   = $class->getMethod('render');
    $method->setAccessible(true);
    $expectedInstance = RedirectResponse::class;
    $this->assertInstanceOf($expectedInstance, $method->invokeArgs($instance, [$request, $this->createMock(TokenMismatchException::class)]));
}

答案 1 :(得分:0)

这样的操作并不容易
$request = $this->createMock(Request::class);
$handler = new Handler($this->createMock(Container::class));
$this->assertInstanceOf(
     RedirectResponse::class,
     $handler->render(
           $request,
           $this->createMock(TokenMismatchException::class)
       )
    );