1

我正在使用 Laravel Passport 为我的 Vue 应用程序构建 API。我可以POST通过浏览器和邮递员发送请求,没有任何问题。

我正在(学习)编写单元测试,并想测试我的store方法。

这是我的示例测试的样子:

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

    $thing = factory(Thing::class)->raw();

    $response = $this->post('api/v1/thing', $thing);

    $response->assertStatus(200);

    $this->assertDatabaseHas('things', $thing);
}

控制器.php

public function store(Request $request)
{
    $attributes = request()->validate([
        'foo' => 'nullable',
        'bar' => 'required',
        'baz' => 'required',
    ]);

    $thing = Thing::create($attributes);

    return response()->json(['data' => $thing], 200);
}

我此时(还)没有检查/设置任何身份验证。也许这就是我要出错的地方。

路线/api.php

Route::prefix('v1')->group(function () {
    Route::post('thing', 'Api\v1\ThingController@store');
});

如果我使用dd($thing),我可以看到所有内容都正确生成,并且我的控制器正在按预期拾取所有内容。

我回来的错误是:

预期状态代码 200 但收到 500。未能断言 false 为 true。

在 Postman 中,如果我向POST同一个控制器发送请求:http://mysite.local/api/v1/thing

一切都很好。

如果我添加RefreshDatabase我的测试通过。我不明白为什么。

我查看了文档并添加了:

...
Passport::actingAsClient(
    factory(Client::class)->create(),
    ['check-status']
);
...

我使用它得到其他额外的错误。我在 Laracasts 上找到了一个建议设置的帖子RefreshDatabase。这似乎使测试通过,我对此感觉不太好。

我如何确定我的测试会奏效?我觉得这是一个非常基础的测试。感谢您的任何建议!

4

0 回答 0