phiremock / phiremock-codeception-extension
PhireMock 的 Codeception 扩展。允许对 HTTP 请求进行远程服务的模拟。
Requires
- php: >=5.6
- codeception/codeception: ^2.2
- phiremock/phiremock: ^1.8
- symfony/process: ^3.1|^2.7.15|^4.0
README
Codeception 扩展和模块,使与 Phiremock 的协作变得更加简单。允许启动一个专门用于运行验收测试的 Phiremock 服务器,或连接到一个已经运行的 Phiremock 服务器。
安装
Composer
此项目已发布在 packagist,因此您只需将其添加到 composer.json 中的依赖项即可
"require-dev": { "mcustiel/phiremock-codeception-extension": "*" }, "minimum-stability": "dev"
注意:Phiremock 使用 react/http 的 dev-master 版本来工作。因此,在 reactphp 小伙子们标记新版本之前,您需要将项目的最小稳定性设置为 dev。
如何使用
扩展
该扩展提供了一种简单的方法来启动配置了主机、端口、调试模式和日志路径的 Phiremock 服务器。
配置
在 codeception.yml 中,您需要启用 Phiremock 扩展并以适当的方式配置它
extensions: enabled: - \Codeception\Extension\Phiremock config: \Codeception\Extension\Phiremock: listen: 127.0.0.1:18080 # defaults to 0.0.0.0:8086 bin_path: ../vendor/bin # defaults to codeception_dir/../vendor/bin logs_path: /var/log/my_app/tests/logs # defaults to codeception's tests output dir debug: true # defaults to false startDelay: 1 # default to 0 expectations_path: /my/expectations/path
注意:自 Codeception 版本 2.2.7 以来,扩展配置可以直接添加到套件配置文件中。这将避免为每个套件启动 phiremock。
Phiremock 在内部使用注解。为了能够运行扩展,必须激活注解自动加载器。为此,您必须在包含您的 composer 自动加载器的引导文件中添加以下行
$loader = require APP_ROOT . '/vendor/autoload.php'; \Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$loader, 'loadClass']);
参数
- listen:指定 Phiremock 必须监听请求的接口和端口
- bin_path:Phiremock "二进制" 文件的路径
- logs_path:输出写入的路径
- debug:将调试数据写入日志文件的位置
- startDelay:Phiremock 启动后等待一段时间再开始运行测试的时间(用于给 Phiremock 启动时间)
- expectations_path:指定一个目录,用于搜索默认要加载的期望定义的 json 文件。
模块
该模块允许您连接到 Phiremock 服务器,并通过代码中的 Codeception 角色以语义化的方式与之交互。
配置
您需要在套件配置文件中启用 Phiremock 模块
modules: enabled: - Phiremock: host: 127.0.0.1 port: 18080 resetBeforeEachTest: false # if set to true, executes `$I->haveACleanSetupInRemoteService` before each test.
使用
该模块提供了以下便捷方法与 Phiremock 服务器通信
expectARequestToRemoteServiceWithAResponse
允许您在 Phiremock 中设置期望,指定预期的请求和服务器应针对它给出的响应
$I->expectARequestToRemoteServiceWithAResponse( Phiremock::on( A::getRequest()->andUrl(Is::equalTo('/some/url')) )->then( Respond::withStatusCode(203)->andBody('I am a response') ) );
haveACleanSetupInRemoteService
清除服务器上所有配置的期望、场景和请求历史记录,并重新加载期望文件。
$I->haveACleanSetupInRemoteService();
dontExpectRequestsInRemoteService
清除所有先前配置的期望和请求历史记录。
$I->dontExpectRequestsInRemoteService();
haveCleanScenariosInRemoteService
清除所有场景的状态(将它们都设置为初始状态)。
$I->haveCleanScenariosInRemoteService();
seeRemoteServiceReceived
允许您验证服务器接收了指定次数的请求。此请求可能是或可能不是先前设置的期望。
$I->seeRemoteServiceReceived(1, A::getRequest()->andUrl(Is::equalTo('/some/url')));
didNotReceiveRequestsInRemoteService
重置 Phiremock 中验证器的请求计数器。
$I->didNotReceiveRequestsInRemoteService();
用例
Yii2-Curl
Yii2-Curl 使用 phiremock-codeception-extension 进行功能测试。您可以查看 扩展 和 模块 的配置,以及 Phiremock 在测试中的 配置方式。