如何使用Phpunit在具有动态URI的Laravel中测试REST API



我正在尝试使用Phpunit测试用Laravel Faramework编写的REST API。这是我的 api.php 文件代码

Route::group([
  'middleware' => ['cors','db.select'],
  'prefix'     => 'v1/{database}',
], function() {
    Route::resource('test-beds', 'TestBedController');
});

其中 CORS中间件允许发送交叉原始资源共享和 db.select middleware 是由我创建的,该是从路由中删除{database}变量的我。

在我的> TestBedController 中,如果我不发送 ID字段使用POST方法,它给出了HTTP状态代码422的响应。要验证我写了以下代码写的内容。

这是我的 testapitest.php 文件

class TestBedApiTest extends TestCase {
  public function testRequiresId() {
    // I tried by adding and removing following line but no luck
    $this->WithoutMiddleware();
    $this->json('POST', 'test-beds')->assertResponseStatus(422);
  }
}

但是它正在返回我 404 ,这很可能是因为它无法找到路由 test> test> test-beds 。我尝试了遵循代码,但没有运气

 $this->json('POST', 'v1/db1/test-beds')->assertResponseStatus(422);
 $this->json('POST', 'api/v1/db1/test-beds')->assertResponseStatus(422);
 $this->json('POST', 'api/v1/test-beds')->assertResponseStatus(422);
 $this->json('POST', 'v1/{database}/test-beds')->assertResponseStatus(422);

通过使用PHP单元& API的测试是个好主意。狗步骤1下载PHP单元&库库帮助我们向API提出请求。您通过命令安装两个作曲家,例如

$ composer require guzzlehttp/guzzle:^6.1 phpunit/phpunit:^5.0

通过安装该库,您将其包含在autoload.php

然后在API中开发测试类后,然后运行函数名称setup()然后通过实现您的功能来测试您的API。

最新更新