【问题标题】:PHPUnit - post to an existing controller does not return an errorPHPUnit - 发布到现有控制器不会返回错误
【发布时间】:2018-07-08 01:13:08
【问题描述】:

我是 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,当我运行测试时,我收到了这个错误,而不是告诉我控制器不存在的错误

断言 null 匹配预期 1 失败。

请问我该如何解决这个问题?

【问题讨论】:

  • 在测试中你想断言 1 等于某事,然后它说它不等于!如果你没有断言路由存在,你为什么期望呢?
  • 我需要使用$this->withoutExceptionHandling() 来触发错误。您的回答对我找到问题的答案很有帮助。

标签: laravel unit-testing phpunit laravel-5.4 laravel-5.5


【解决方案1】:

您可能没有在 Controller 中创建方法,但这并不意味着您的测试将停止。
测试运行。它调用您的端点。它返回 404 状态,因为在控制器中找不到方法。
然后你做出一个断言,因为你的发布请求将失败 没有成功,也没有为您的员工创建任何组。

只需添加一个状态断言$response->assertStatus(code)
$response->assetSuccessful()

【讨论】:

    【解决方案2】:

    这个异常是由 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 2018-06-20
      • 1970-01-01
      • 2012-12-26
      • 2012-12-30
      相关资源
      最近更新 更多