PHPackages                             czukowski/phpunit-mock-dibi - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. czukowski/phpunit-mock-dibi

ActiveLibrary[Testing &amp; Quality](/categories/testing)

czukowski/phpunit-mock-dibi
===========================

Dibi mocking helpers for PHPUnit

4.2(5y ago)11.7k1[1 PRs](https://github.com/czukowski/phpunit-mock-dibi/pulls)MITPHP

Since Oct 4Pushed 2y agoCompare

[ Source](https://github.com/czukowski/phpunit-mock-dibi)[ Packagist](https://packagist.org/packages/czukowski/phpunit-mock-dibi)[ Docs](https://github.com/czukowski/phpunit-mock-dibi)[ RSS](/packages/czukowski-phpunit-mock-dibi/feed)WikiDiscussions master Synced 2w ago

READMEChangelogDependencies (3)Versions (14)Used By (0)

Dibi mocking helpers for PHPUnit
================================

[](#dibi-mocking-helpers-for-phpunit)

[![PHPUnit](https://github.com/czukowski/phpunit-mock-dibi/workflows/PHPUnit/badge.svg)](https://github.com/czukowski/phpunit-mock-dibi/workflows/PHPUnit/badge.svg)

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.

This is an adapted version of [czukowski/phpunit-mock-db](https://packagist.org/packages/czukowski/phpunit-mock-db) package for uses of [Dibi - smart database layer for PHP](https://github.com/dg/dibi) by David Grudl. Dibi is a database connection library that includes a powerful query builder and supports a variety of relational database systems.

Installation
------------

[](#installation)

Install using Composer:

```
composer require czukowski/phpunit-mock-dibi
```

- Dibi version 4.x is supported with PHP 7.2 or newer.
- Dibi version 3.x is supported with PHP 5.6 or newer.

Usage
-----

[](#usage)

Use `Cz\PHPUnit\MockDibi\MockTrait` trait in a test case class, this will enable methods for creating database mock instances. Just call `createDatabaseMock` method passing a `Dibi\Connection`instance that uses one of the mock drivers provided in this package, and a mock object will be added to it and registered to the test case class.

There is a handy factory class for mock Dibi drivers in `Cz\PHPUnit\MockDibi\Drivers\DriversFactory`so you don't have to create driver instances yourself (see its source code for methods available).

### Example how to create mock Dibi Connection:

[](#example-how-to-create-mock-dibi-connection)

```
$dibi = new Dibi\Connection([
    'driver' => $factory->createMySqlDriver()  // or whatever other driver you may be needing.
]);
```

### Examples how to set up expected queries and mock results:

[](#examples-how-to-set-up-expected-queries-and-mock-results)

Return a pre-defined result set on *any* database query:

```
$this->createDatabaseMock($dibi)
    ->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($dibi)
    ->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.

*Also note*: different Dibi drivers may use different characters to quote identifiers, eg. backticks for MySQL or square brackets for MS SQL Server, etc. Query constraints will use Dibi Translator to transform queries so there's no need to take extra care to have identifiers quotes matching the currently used driver.

```
$mock = $this->createDatabaseMock($dibi);
$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($dibi);
$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:

```
$this->createDatabaseMock($dibi)
    ->expects($this->exactly(3))
    ->query('INSERT INTO `t1` VALUES ("a", "b", "c")')
    ->willSetLastInsertId(1, 2, 3);
```

Return affected rows count:

```
$this->createDatabaseMock($dibi)
    ->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($dibi)
    ->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($dibi)
    ->expects($this->exactly(4))
    ->query($this->stringStartsWith('INSERT'))
    ->onConsecutiveCalls()
    ->willSetLastInsertId(1)
    ->willSetLastInsertId(2)
    ->willThrowException(new RuntimeException('Deadlock'))
    ->willSetLastInsertId(3);
```

Although not normally needed, it is possible to set up custom callbacks to handle database queries (callbacks don't have to return anything):

```
$mock = $this->createDatabaseMock($dibi);
$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($dibi);
$mock->setRequireMatch(FALSE);
```

License
-------

[](#license)

This work is released under the MIT License. See LICENSE.md for details.

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~81 days

Recently: every ~151 days

Total

11

Last Release

2018d ago

Major Versions

3.0.1 → 4.0.12018-12-14

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/186792?v=4)[Korney Czukowski](/maintainers/czukowski)[@czukowski](https://github.com/czukowski)

---

Top Contributors

[![czukowski](https://avatars.githubusercontent.com/u/186792?v=4)](https://github.com/czukowski "czukowski (70 commits)")

---

Tags

databasedibimockphpunitsqlphpunitdatabasemockdibi

### Embed Badge

![Health badge](/badges/czukowski-phpunit-mock-dibi/health.svg)

```
[![Health](https://phpackages.com/badges/czukowski-phpunit-mock-dibi/health.svg)](https://phpackages.com/packages/czukowski-phpunit-mock-dibi)
```

###  Alternatives

[php-mock/php-mock-phpunit

Mock built-in PHP functions (e.g. time()) with PHPUnit. This package relies on PHP's namespace fallback policy. No further extension is needed.

1719.0M527](/packages/php-mock-php-mock-phpunit)[donatj/mock-webserver

Simple mock web server for unit testing

1402.7M96](/packages/donatj-mock-webserver)[blastcloud/guzzler

Supercharge your app or SDK with a testing library specifically for Guzzle.

272451.0k42](/packages/blastcloud-guzzler)[nunomaduro/mock-final-classes

Allows mocking of final methods and classes in PHP.

114981.2k28](/packages/nunomaduro-mock-final-classes)[colinodell/psr-testlogger

PSR-3 compliant test logger based on psr/log v1's, but compatible with v2 and v3 too!

1813.8M75](/packages/colinodell-psr-testlogger)[icecave/isolator

Dependency injection for global functions.

351.4M29](/packages/icecave-isolator)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
