mcannucci/phnock

此包已被弃用,不再维护。没有建议的替代包。
此包的最新版本(0.1.0)没有可用的许可信息。

模拟HTTP请求

0.1.0 2020-12-29 15:12 UTC

This package is auto-updated.

Last update: 2021-04-29 01:13:04 UTC


README

在PHP测试中模拟网络请求

入门

安装

composer require --dev mcannucci/phnock

引导

在引导文件中包含Phnock::bootstrap()方法,包括需要拦截的所有目录

<?php

use Phnock\Phnock;

// options are:
// directories => which directories to mock
// temporaryFilesDir => where to save the temporary files, by default it is /tmp/
// disableCaching => whether aspect classes should use their previously creating files if there are no changes
require __DIR__ . "/../vendor/autoload.php";
Phnock::bootstrap([
  'directories' => [
    __DIR__.'/../src',
    __DIR__.'/../vendor/guzzle',
  ]
]);

使用

在您的测试用例中包含特质"Phnock\Traits\HTTPMock",并调用方法"$this->matchUriWithResponse"

<?php

use Phnock\Traits\HTTPMock;
use PHPUnit\Framework\TestCase;

class MyTest extends TestCase
{
 use HTTPMock

 public function test_my_test()
 {
   $this->matchUriWithResponse('example.com', 'Intercepted!');
   // Network Request to 'example.com' from either curl or guzzle
   $this->assertEquals($response, 'Intercepted!');
 }
}

可能的返回类型

使用正则表达式模式匹配URL

// This will return 'Intercepted!' for any url that matches this regex
// Ex:
//  https\\example.com?paramter=1
//  https\\example.com?paramter=2
$this->matchUriWithResponse('/https\\\\example\.com\?parameter=.+/','Intercepted');

可能的响应体

// Use a file's contents as the body
$this->matchUriWithResponse(
 'example.com', 
 Phnock\ResponseTypes\FileResponse::of('filepath')
);
// Use an array that will be returned as json
$this->matchUriWithResponse(
 'example.com', 
 [
  'a' => [
   'b' => 'c'
  ]
 ]
);
// Use an iterable to change the contents of the response by how many times it's called
$this->matchUriWithResponse(
 'example.com',
 use Phnock\ResponseTypes\IterableResponse::from(['1','2','3'])
);

开发

提供的Docker Compose配置可用于构建开发环境

docker-compose up -d
# Creating a shell inside the container
docker-compose run -rm php bash
# running phpstan and tests
composer all
# running only the tests
composer test
# running phpstan
composer analyse

构建于

版本控制

版本控制使用SemVer。有关可用版本,请参阅此存储库的标签

许可

本项目采用MIT许可 - 有关详细信息,请参阅LICENSE.md文件

致谢