benjy80
benjy80

Reputation: 195

PHPUnit Laravel : How to Unit Test custom Exception Handler?

I try to make unit test of a custom Exception Handler class (located in app/Exceptions/Handler.php), but i don't know how to do it ...

I don't know how to raise an exception with my mock Request.

Is someone can help me ?

Here is the "render" method :

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

And this is my test case :

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

Upvotes: 5

Views: 4948

Answers (2)

Nahuelsgk
Nahuelsgk

Reputation: 126

It's not easier do something like

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

Upvotes: 0

benjy80
benjy80

Reputation: 195

This how i do it :

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

Upvotes: 3

Related Questions