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



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

我不知道如何使用我的模拟请求提出异常。

有人可以帮助我吗?

这是"渲染"方法:

/**
 * @param IlluminateHttpRequest $request
 * @param Exception $e
 * @return IlluminateHttpRedirectResponse|SymfonyComponentHttpFoundationResponse
 */
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)]));
}

这是我怎么做的:

/**
 * @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)]));
}

做这样的事情并不容易

$request = $this->createMock(Request::class);
$handler = new Handler($this->createMock(Container::class));
$this->assertInstanceOf(
     RedirectResponse::class,
     $handler->render(
           $request,
           $this->createMock(TokenMismatchException::class)
       )
    );

相关内容

  • 没有找到相关文章

最新更新