kirouane/imposter

PHPUnit 的 API 模拟

1.0.0 2019-03-07 10:39 UTC

This package is auto-updated.

Last update: 2024-09-10 18:34:02 UTC


README

Travis Coverage Status

Imposter

Imposter 是一个用于提供 HTTP 静态和模拟的 PHP 库。

以下是一个示例,强调如何使用此库在 PHPUnit 中模拟 HTTP 端点是多么简单。

namespace Imposter;

use PHPUnit\Framework\TestCase;

/**
 * Class ScenarioTest
 * @package Imposter
 */
class ReadMeTest extends TestCase
{
    /**
     * @test
     *
     */
    public function match()
    {
        ImposterFactory::get()->mock(8081)
            ->withPath('/users/1')
            ->withMethod('POST')
            ->returnBody('{"response" :"okay"}')
            ->once()
            ->send();

        $client   = new \GuzzleHttp\Client();
        $response = $client->post('https://:8081/users/1')->getBody()->getContents();
        self::assertSame($response, '{"response" :"okay"}');
    }

    public function tearDown()
    {
        ImposterFactory::get()->close();
    }
}

安装

composer require kirouane/imposter --dev

功能

显示日志

如果 HTTP 请求没有匹配任何模拟,你可以在这里找到原因 https://:2424/mock/log/html

下面,你可以看到日志页面的样子。

Logs

PHPUnit 断言

Imposter 库使用 PHPunit 断言来匹配你创建的模拟与 HTTP 请求。

示例

namespace Imposter;

use PHPUnit\Framework\TestCase;

/**
 * Class ScenarioTest
 * @package Imposter
 */
class ReadMeTest extends TestCase
{
    /**
     * @test
     */
    public function match()
    {
        ImposterFactory::get()->mock(8081)
            ->withPath('/users/1')
            ->withMethod(new RegularExpression('/POST|PUT/'))
            ->returnBody('{"response" :"okay"}')
            ->twice()
            ->send();

        $client   = new \GuzzleHttp\Client();
        $response = $client->post('https://:8081/users/1')->getBody()->getContents();
        self::assertSame($response, '{"response" :"okay"}');

        $response = $client->put('https://:8081/users/1')->getBody()->getContents();
        self::assertSame($response, '{"response" :"okay"}');
    }

    public function tearDown()
    {
        ImposterFactory::get()->close();
    }

}

代理

尚未实现