thanos-kontos / amock
PHPunit 模拟测试夹具
0.0.3
2017-11-16 20:58 UTC
Requires
- php: >=7.1
- phpunit/phpunit: ^6.0
- symfony/yaml: ^2.7 || ^3.0 || ^4.0
Requires (Dev)
- codeclimate/php-test-reporter: ^0.4.4
This package is not auto-updated.
Last update: 2024-09-29 04:37:10 UTC
README
发行说明
仍然不稳定。请谨慎使用
快速浏览
引用自 phpunit
有时候测试被测系统(SUT)非常困难,因为它依赖于其他无法在测试环境中使用的组件。这可能是因为它们不可用,它们不会返回测试所需的输出,或者执行它们会有不良的副作用。在其他情况下,我们的测试策略需要我们拥有更多对SUT内部行为的控制或可见性。
当我们编写一个无法(或选择不)使用真实依赖组件(DOC)的测试时,我们可以用测试替身(Test Double)来替换它。测试替身不需要完全像真实DOC那样行为;它只需要提供与真实组件相同的API,以便SUT认为它是真实的!
不模拟对象就很难写出好的测试,因为我们经常需要模拟写入数据库或调用外部服务。
Amock 允许您使用yaml而不是“污染”测试代码来创建这些存根对象。
说明
composer require --dev thanos-kontos/amock
添加一个存储夹具的目录,例如 tests/mock_fixtures
,然后添加您想要的任何yaml文件。
# tests/mock_fixtures/repositories.yml MyProject\Library\UserRepository: mockUserRepository: disableConstructor: true mockMethods: insert: '@null' update: '@null' MyProject\Library\ProductRepository: mockProductRepository: disableConstructor: true mockMethods: insert: '@null' update: '@null'
# tests/mock_fixtures/gateways.yml MyProject\Library\SomeApiGateway: mockSuccessResponse: disableConstructor: true mockMethods: getHelloReponse: '@string:{"hello":"world"}' mock404Response: disableConstructor: true mockMethods: getHelloReponse: '@string:{"error": "404","message":"Not found"}' sampleSetter: '@self' methodThatReturnsDifferentValueOnConsecutiveCalls: - '@string:{"hello":"world"}' - '@integer:123' - '@boolean:false' methodThatReturnsArray: '@array:{"111":"aaa","222":"bbb"}' methodThatReturnsBoolean: '@boolean:false' methodThatReturnsInteger: '@integer:123' methodThatReturnsNull: '@null' mockExceptionResponse: disableConstructor: true mockMethods: getHelloReponse: '@exception:\MyProject\Library\Exception\ApiException'
在您的测试 setUp 方法中
$config = new \Amock\Configuration('yaml', 'dir', '/path/to/mock_fixtures'); $this->amock = \Amock\Amock::create($config, $testCase);
或者
$config = new \Amock\Configuration('yaml', 'file', '/path/to/mock_fixtures/somefile.yml'); $this->amock = \Amock\Amock::create($config, $testCase);
然后您可以在测试中使用配置的模拟
$stub = $this->amock->get('mock404Response');
示例
这里有一个模拟项目 示例,您可以用作参考。
许可
Amock 在 MIT 许可证 下发布。