czukowski/phpunit-mock-db
Composer 安装命令:
composer require czukowski/phpunit-mock-db
包简介
Database Abstraction Layer mocking helpers for PHPUnit
README 文档
README
A mock-object library for database queries testing, without having to initialize in-memory database from fixtures. Rather, every query executed by a tested code can be set to return a pre-defined result set, affected rows count or last insert ID. All with a familiar interface similar to PHPUnit Mock Objects.
Installation
composer require czukowski/phpunit-mock-db
Version numbering follows major PHPUnit version numbers, so for a given PHPUnit N.x, you'll get the appropriate version of this package (this should happen automatically).
Usage
Use Cz\PHPUnit\MockDB\MockTrait trait in a test case class, this will enable methods for
creating database mock instances. A 'fake' driver for a database abstraction layer used in the
tested code must be used, which implements both Cz\PHPUnit\MockDB\DatabaseDriverInterface
interface and that of the database abstraction layer's, additionally getDatabaseDriver method
must be implemented by the test case class, that returns an instance of that driver.
Note: This covers just the most simple and the most common use case for testing against a single
database connection, and the trait has been designed accordingly. If it is required to have multiple
database connections mocked at the same time or a different way to inject dependencies into the
tested code, a different implementation of MockTrait may be needed. But the trait is extremely
simple, especially in comparison to the 'fake' driver implementation that is needed anyway, you can
clone and adjust the trait for your project or come up with a completely different implementation.
Examples:
Return a pre-defined result set on any database query:
$this->createDatabaseMock() ->expects($this->any()) ->willReturnResultSet([ ['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar'], ]);
Return a pre-defined result set on any database query and expect it to be executed exactly once:
$this->createDatabaseMock() ->expects($this->once()) ->willReturnResultSet([ ['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar'], ]);
Return a pre-defined result set on each specific database query, expecting each query to be executed exactly once:
Note: the order in which the query expectations are being set up doesn't have to be same as the order in which the queries will be executed.
Also note: the whitespaces will be ignored in query constraints, so they can be loaded from well-formatted files, which could be especially useful for long and complex queries.
$mock = $this->createDatabaseMock(); $mock->expects($this->once()) ->query('SELECT * FROM `t1`') ->willReturnResultSet([['id' => 1, 'name' => 'foo']]); $mock->expects($this->once()) ->query('SELECT * FROM `t2`') ->willReturnResultSet([['id' => 2, 'name' => 'bar']]);
Expect mixed queries, some at specific invocations (note: SELECT query is set to return an empty result set):
$mock = $this->createDatabaseMock(); $mock->expects($this->at(1)) ->query('INSERT INTO `t1` VALUES (1, "foo")') ->willSetLastInsertId(1); $mock->expects($this->at(2)) ->query('INSERT INTO `t1` VALUES (2, "bar")') ->willSetLastInsertId(2); $mock->expects($this->once()) ->query('SELECT * FROM `t1`') ->willReturnResultSet([]);
Expect same query executed exactly three times and return different last insert IDs on each consecutive call, also note how this query is parametrized:
$this->createDatabaseMock() ->expects($this->exactly(3)) ->query('INSERT INTO `t1` VALUES (?, ?, ?)') ->with(['a', 'b', 'c']) ->willSetLastInsertId(1, 2, 3);
Return affected rows count:
$this->createDatabaseMock() ->expects($this->exactly(2)) ->query('UPDATE `t1` SET `foo` = "bar" WHERE `id` = 1') ->willSetAffectedRows(1);
Match SQL query using PHPUnit constraint (note: whitespace will not be ignored when using default PHPUnit constraints):
$this->createDatabaseMock() ->expects($this->once()) ->query($this->stringStartsWith('SELECT')) ->willReturnResultSet([['id' => 1, 'name' => 'foo']]);
Set up different outcomes on consecutive calls for INSERT queries using a consecutive calls stub builder:
$this->createDatabaseMock() ->expects($this->exactly(4)) ->query($this->stringStartsWith('INSERT')) ->onConsecutiveCalls() ->willSetLastInsertId(1) ->willSetLastInsertId(2) ->willThrowException(new RuntimeException('Deadlock')) ->willSetLastInsertId(3);
Set up custom callbacks to handle database queries (callbacks don't have to return anything):
$mock = $this->createDatabaseMock(); $mock->expects($this->any()) ->query($this->stringStartsWith('INSERT')) ->willInvokeCallback(function ($invocation) { $invocation->setLastInsertId(1); }); $mock->expects($this->any()) ->query($this->stringStartsWith('UPDATE')) ->willInvokeCallback(function ($invocation) { $invocation->setAffectedRows(0); }); $mock->expects($this->any()) ->query($this->stringStartsWith('SELECT')) ->willInvokeCallback(function ($invocation) { $invocation->setResultSet([]); });
By default, mock object is set to throw an exception if an unknown (unmatched) query is executed, but this can be disabled:
$mock = $this->createDatabaseMock(); $mock->setRequireMatch(FALSE);
License
This work is released under the MIT License. See LICENSE.md for details.
czukowski/phpunit-mock-db 适用场景与选型建议
czukowski/phpunit-mock-db 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 24.03k 次下载、GitHub Stars 达 3, 最近一次更新时间为 2018 年 04 月 09 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「database」 「phpunit」 「mock」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 czukowski/phpunit-mock-db 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 czukowski/phpunit-mock-db 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 czukowski/phpunit-mock-db 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
LazyPDO is a set of wrappers over PHP's standard PDO and PDOStatement classes. It enables lazy loading, serialization and decoration.
Dibi is Database Abstraction Library for PHP
HiDev plugin for PHPUnit
Testing Suite For Lumen like Laravel does.
A cli tool which generates unit tests.
Store your language lines in the database, yaml or other sources
统计信息
- 总下载量: 24.03k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 3
- 点击次数: 2
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2018-04-09