laravel phpunit withexceptionhandling

廉价感情. 提交于 2019-12-07 15:50:04

问题


I'm in the process of writing a web app using Laravel 5.5 and Vue.js. PHPUnit version is 6.3.1.

I'm testing for validation errors when a user registers using Form Requests.

Route:

// web.php
Route::post('/register', 'Auth\RegisterController@store')->name('register.store');

This is my passing test:

/** @test */
function validation_fails_if_username_is_missing()
{
    $this->withExceptionHandling();

    $this->json('POST', route('register.store'), [
        'email' => 'johndoe@example.com',
        'password' => 'secret',
        'password_confirmation' => 'secret'
    ])->assertStatus(422);
}

However, it fails when I remove exception handling:

/** @test */
function validation_fails_if_username_is_missing()
{
    $this->json('POST', route('register.store'), [
        'email' => 'johndoe@example.com',
        'password' => 'secret',
        'password_confirmation' => 'secret'
    ])->assertStatus(422);
}

I do not understand why this test fails without exception handling as it's stated in the Laravel documentation that

If the request was an AJAX request, a HTTP response with a 422 status code will be returned

I already tried to declare this particular route in the api middleware group, but that didn't change anything.

Can someone with more experience than I do explain to me why that is? Thanks in advance.

EDIT: This is the content of my Handler.php class file. I don't think anything was edited.

protected $dontReport = [
    \Illuminate\Auth\AuthenticationException::class,
    \Illuminate\Auth\Access\AuthorizationException::class,
    \Symfony\Component\HttpKernel\Exception\HttpException::class,
    \Illuminate\Database\Eloquent\ModelNotFoundException::class,
    \Illuminate\Session\TokenMismatchException::class,
    \Illuminate\Validation\ValidationException::class,
];


public function report(Exception $exception)
{
    parent::report($exception);
}

public function render($request, Exception $exception)
{
    return parent::render($request, $exception);
}

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest(route('login'));
}

来源:https://stackoverflow.com/questions/46473103/laravel-phpunit-withexceptionhandling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!