【问题标题】:How to test REST api in laravel having dynamic URI using phpunit如何使用phpunit在具有动态URI的laravel中测试REST api
【发布时间】:2018-05-24 20:23:42
【问题描述】:

我正在尝试使用 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 中间件 由我创建,它从路由中删除了 {database} 变量。

在我的 TestBedController 中,如果我不使用 post 方法发送 id 字段,它会给出 HTTP 状态代码 422 的响应。为了验证我是否编写了以下代码。

这是我的 TestBedApiTest.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-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 laravel phpunit laravel-5.3


    【解决方案1】:

    API 测试是个好主意,通过使用 PHP 单元和 guzzle 第 1 步下载 PHP 单元 & guzzle 该库帮助我们向 API 发出请求。 您可以通过

    之类的命令安装这两个作曲家
    $ composer require guzzlehttp/guzzle:^6.1 phpunit/phpunit:^5.0
    

    通过安装您包含在autoload.php 中的库

    然后在api中开发测试类然后运行函数名setup() 然后通过实现你的函数来测试你的 api。

    【讨论】:

      猜你喜欢
      • 2021-04-04
      • 2012-09-08
      • 2014-12-31
      • 2018-10-23
      • 2012-07-16
      • 2015-09-26
      • 2016-12-31
      • 1970-01-01
      • 2023-03-24
      相关资源
      最近更新 更多