PHPUnit - post 现有控制器不会 return 错误

PHPUnit - post to an existing controller does not return an error

我是 PHPUnit 和 TDD 的新手。我刚刚将我的项目从 Laravel 5.4 升级到 5.5,并安装了 phpunit 6.5.5。在学习过程中,我写了这个测试:

/** @test */
public function it_assigns_an_employee_to_a_group() {
    $group = factory(Group::class)->create();

    $employee = factory(Employee::class)->create();

    $this->post(route('employee.manage.group', $employee), [
        'groups' => [$group->id]
    ]);

    $this->assertEquals(1, $employee->groups);
}

我在 web.php 文件中定义了一条路由,如下所示

Route::post('{employee}/manage/groups', 'ManageEmployeeController@group')
    ->name('employee.manage.group');

我还没有创建 ManageEmployeeController 并且当我 运行 测试时,我没有得到一个错误告诉我控制器不存在,而是得到这个错误

Failed asserting that null matches expected 1.

请问如何解决这个问题?

您可能没有在 Controller 中创建方法,但这并不意味着您的测试将停止。
测试 runs.It 调用您的端点。它 returns 404 状态,因为找不到控制器中的方法。
然后你做出一个断言,自你的 post 请求以来,该断言将失败 没有成功,没有为您的员工创建组。

只需添加状态声明$response->assertStatus(code)
$response->assetSuccessful()

异常由 Laravel 自动处理,所以我使用

禁用了它
$this->withoutExceptionHandling();

现在的测试方法是这样的:

/** @test */
public function it_assigns_an_employee_to_a_group() {

    //Disable exception handling
    $this->withoutExceptionHandling();

    $group = factory(Group::class)->create();

    $employee = factory(Employee::class)->create();

    $this->post(route('employee.manage.group', $employee), [
        'groups' => [$group->id]
    ]);

    $this->assertEquals(1, $employee->groups);
}