【问题标题】:Lumen 5.5 unit-test post jsonLumen 5.5 单元测试后 json
【发布时间】:2018-02-27 13:45:03
【问题描述】:

学习 Lumen v5.5 php 框架并在创建我的第一个 php 单元测试时遇到了障碍。如果我设置 URL 并选择 POST 方法并在正文中选择“raw”并将类型设置为“application/json”,则该应用程序使用 Postman 工作。所以我们已经知道帖子有效,只是想进行一个测试。

这是我认为的工作单元测试应该是最接近的东西:

public function testPostJson() {
    $the_json    = '{"client_guid": "C00A0EA5-3F64-01EA-C4B6-159EA145AB3B"}';
    $the_headers = [ 'CONTENT_TYPE' => 'application/json' ];
    $this->call(
        'POST',
        '/getClientNotes',
        [],
        [],
        [],
        $the_headers,
        $the_json
    );
    $this->assertResponseOk();
    $this->assertEquals(true, $this->response->status);
}

但它当然会返回如下错误:

  • 1) NotesTest::testPostJson 预期状态码 200,得到 404.*
  • 2) 错误异常:未定义属性: 照亮\Http\Response::$status

即使在 lumen docs 网站上,文档的方式也不多: https://lumen.laravel.com/docs/5.5/testing

【问题讨论】:

  • 路由是为 POST 还是 GET 创建的? getClientNotes 听起来像是一个 GET 请求。
  • 不,不是获取它的 POST,这里是路由:$app->post('note/getClientNotes', 'NoteController@getClientNotes');
  • 废话,这是我的第一个错误...'/getClientNotes',应该是'note'/getClientNotes',

标签: php unit-testing testing lumen


【解决方案1】:

这里是工作代码...我错过了 $this->call() 的第二个参数中的“note/”。

class NotesTest extends TestCase {

protected $send_headers = null;
protected $send_json = null;
protected $receive_json = null;

public function testIsApiAlive() {
    $this->call("GET",'/');
    $this->assertEquals($this->app->version(), $this->response->getContent());
    $this->assertEquals(200, $this->response->status());
}

public function testPostJson() {
    $this->send_json    = '{"client_guid": "C00A0EA5-3F64-01EA-C4B6-159EA145AB3B"}';
    $this->send_headers = [ 'CONTENT_TYPE' => 'application/json' ];
    $this->call(
        'POST',
        'note/getClientNotes',
        [],
        [],
        [],
        $this->send_headers,
        $this->send_json
    );
    $this->receive_json = json_decode($this->response->getContent());
    $this->assertEquals(200, $this->response->status());
    $this->assertTrue(isset($this->receive_json->status));
    $this->assertTrue($this->receive_json->status == true);
    $this->assertTrue(isset($this->receive_json->data[0]->agency));
    $this->assertTrue($this->receive_json->data[0]->agency == 'demo');
}

这是命令行结果:

C:\xampp\htdocs\jsonproject\tests\>phpunit NotesTest.php
PHPUnit 5.7.21 by Sebastian Bergmann and contributors.

..                                                                  2 / 2 (100%)

Time: 740 ms, Memory: 10.00MB

OK (2 tests, 7 assertions)

【讨论】:

    猜你喜欢
    • 2018-03-06
    • 2017-11-23
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    • 2019-07-31
    • 1970-01-01
    • 2018-12-19
    相关资源
    最近更新 更多