7

我有以下测试:

public function testStoreMemberValidation()
{
    $response = $this->withExceptionHandling()->post('/api/members', [
        "name" => "Eve",
        "age" => "invalid"
    ], ['X-Requested-With' => 'XMLHttpRequest']);

    dd($response->json());
};

我试图断言响应是验证错误的形式。控制器方法如下:

public function store(Request $request)
{
    $data = $request->validate([
        'name' => 'required|string',
        'age' => 'required|integer',
    ]);

    Member::create($data);
}

但是,每当我调用任何调用$response->json()(其中大多数)的断言时,我都会遇到异常:

Illuminate\Validation\ValidationException :给定的数据无效。

如何在不引发此错误的情况下对此响应执行断言?

注意,我使用的是 Laravel 5.7。

4

1 回答 1

11

你有withExceptionHandling()你的测试,删除它,它应该可以工作。

$response = $this->withExceptionHandling()->post('/api/members', [
        "name" => "Eve",
        "age" => "invalid"
    ], ['X-Requested-With' => 'XMLHttpRequest']);

应该

$response = $this->post('/api/members', [
            "name" => "Eve",
            "age" => "invalid"
        ], ['X-Requested-With' => 'XMLHttpRequest']);
于 2019-04-21T22:24:55.873 回答