3

我正在使用 Laravel 5.5 和 Vue.js 编写一个 Web 应用程序。PHPUnit 版本是 6.3.1。

当用户使用表单请求注册时,我正在测试验证错误。

路线:

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

这是我的及格测试:

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

但是,当我删除异常处理时它会失败:

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

我不明白为什么这个测试在没有异常处理的情况下失败,正如 Laravel 文档中所述

如果请求是 AJAX 请求,将返回带有 422 状态码的 HTTP 响应

我已经尝试在 api 中间件组中声明这个特定的路由,但这并没有改变任何东西。

比我更有经验的人可以向我解释为什么会这样吗?提前致谢。

编辑:这是我的 Handler.php 类文件的内容。我认为没有任何内容被编辑。

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'));
}
4

0 回答 0