在 [slim] 中伪造 Request 来进行你的 HTTP 测试吧

  • 代码需要做HTTP测试,Laravel中有自带这方面的功能。现在使用slim就得自己动手丰衣足食。
  • 网上找了许多例子,关于这方便的比较少。然后就想到了查看Laravel的源码
  • 看了一下,发现其实是自己伪造一个Request对象,然后执行返回结果
  • 然后自己也参考这个在slim中实现

    构建好测试文件

  • composer.json加入以下内容自动加载,并执行composer dump-auto
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    }
  • 根目录新建配置文件phpunit.xml内容如下
<phpunit bootstrap="tests/bootstrap.php">
    <testsuites>
        <testsuite name="Feature">
            <directory suffix="Test.php">tests</directory>
        </testsuite>
    </testsuites>
</phpunit>
  • tests/bootstrap.php文件内容如下
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
    $name = $args['name'];
    $response->getBody()->write("Hello, $name");
    return $response;
});

$app->get('/api/v1/users', function (Request $request, Response $response) {

    $data = [['name' => 'Bob', 'age' => 40]];
    $payload = json_encode($data);

    $response->getBody()->write($payload);
    return $response
        ->withHeader('Content-Type', 'application/json');
});

// 这里不要运行 app
// $app->run();
// 并且声明一个函数得到 App 对象
function getApplication()
{
    global $app;

    return $app;
}
  • 创建测试文件tests/HomeTest.php写入一下内容
<?php

namespace Tests;
use Nyholm\Psr7\Uri;
use PHPUnit\Framework\TestCase;
use Slim\Factory\ServerRequestCreatorFactory;

class HomeTest extends TestCase
{
    public function testHello()
    {
        $name = 'Bob';

        $serverRequestCreator = ServerRequestCreatorFactory::create();
        $request = $serverRequestCreator->createServerRequestFromGlobals();

        $uri = new Uri();
        $request = $request->withUri($uri->withPath("/hello/{$name}"));

        $response = getApplication()->handle($request);
        $responseContent = (string)$response->getBody();

        $this->assertEquals($responseContent, "Hello, {$name}");
    }

    public function testJsonApi()
    {
        $serverRequestCreator = ServerRequestCreatorFactory::create();
        $request = $serverRequestCreator->createServerRequestFromGlobals();

        // 因为 Uri 和 Request 对象都是不可以修改的,所以都需要新建
        $uri = new Uri();
        $request = $request->withUri($uri->withPath('api/v1/users'));
        // 如果需要伪造查询参数可以这样子做
        // $request = $request->withQueryParams([]);
        // 使用全局函数拿到 App, 传入伪造的 Request,得到处理之后的 Response
        $response = getApplication()->handle($request);

        // 需要用 (string) 强转,不要直接 $response->getBody()->getContents()
        // 区别就是强转,在实现类把读取指针重置到了第一位,防止得不到完整的内容
        $responseContent = (string)$response->getBody();

        $this->assertJson($responseContent);
    }
}
  • 最后的最后,执行phpunit得到测试结果
$ phpunit
PHPUnit 7.5.17 by Sebastian Bergmann and contributors.

..                                                                  2 / 2 (100%)

Time: 45 ms, Memory: 4.00 MB

OK (2 tests, 2 assertions)

原文链接 http://www.shiguopeng.cn/archives/431

本作品采用《CC 协议》,转载必须注明作者和本文链接
当神不再是我们的信仰,那么信仰自己吧,努力让自己变好,不辜负自己的信仰!
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
41
粉丝
158
喜欢
711
收藏
347
排名:30
访问:22.2 万
私信
所有博文
社区赞助商