【问题标题】:How can I test DELETE api in Laravel?如何在 Laravel 中测试 DELETE api?
【发布时间】:2020-02-06 17:28:18
【问题描述】:

如何使用 Codeception 在 Laravel 中测试 DELETE 的 RESTful api?

我使用以下函数:


    public function authenticatedUserSuccessDeleteEmployee(ApiTester $I)
    {
        $I->wantToTest('authenticated super user success delete employee');
        // set header authorization
        $I->amBearerAuthenticated($this->token);
        //
        $this->employee = factory(\App\Models\Employee::class)->create([
            'id' => '20200100000000'
        ]);        
        // see database row is containing our expected data
        $I->seeRecord('employees', ['id' => '20200100000000']);
        // Send delete request
        $I->sendDELETE('employees', array('id' => '20200100000000'));
        // check expected response code is 200 OK
        $I->seeResponseCodeIs(200);
    } 

但是员工没有在数据库中创建!

如何创建用于测试删除 API 的对象?

【问题讨论】:

  • 简短回答是“是”
  • 如果你使用的是phpunit,你可以做一个集成测试,所以首先你需要在数据库中创建对象。然后调用你的 api endoint(例如通过对象 id)。之后,您必须使用在第一步中创建并被您的 api 删除的相同 id 查询您的数据库。结果应该是空的,这可以确保端点确实删除了对象
  • 问题是这个测试会失败!错误是The requested resource was not found. 这意味着该对象不是在数据库中创建的。
  • 我也想使用Codeception。我正在寻找使用Codeception 在 Laravel 中测试 DELETE api 的示例。例如在这里我找到了一些用于测试创建的东西:medium.com/teknomuslim/… 但是找不到任何用于测试 DELETE api 的示例。
  • 如果你硬编码 `seeRecord 中的 id,为什么还要$id = $this->getExpectedId()

标签: php laravel testing codeception


【解决方案1】:

我发现了问题。我需要将 id 作为 url 的一部分发送!

$I->sendDELETE('employees/20200100000000');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 2022-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 2019-02-17
    相关资源
    最近更新 更多