PHPackages                             czukowski/phpunit-mock-db - 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-db

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

czukowski/phpunit-mock-db
=========================

Database Abstraction Layer mocking helpers for PHPUnit

9.0(6y ago)323.0k↓100%1MITPHP

Since Apr 9Pushed 5y agoCompare

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

READMEChangelogDependencies (2)Versions (50)Used By (0)

Database Abstraction Layer mocking helpers for PHPUnit
======================================================

[](#database-abstraction-layer-mocking-helpers-for-phpunit)

[![PHPUnit](https://github.com/czukowski/phpunit-mock-db/workflows/PHPUnit/badge.svg)](https://github.com/czukowski/phpunit-mock-db/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.

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

[](#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
-----

[](#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:

[](#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
-------

[](#license)

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

###  Health Score

38

—

LowBetter than 86% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity31

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity76

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 ~17 days

Total

40

Last Release

2223d ago

Major Versions

5.0.3 → 6.0.32018-10-04

6.0.3 → 7.0.42018-10-04

7.4.0 → 8.02019-02-15

6.0.4 → 8.0.12019-04-05

5.0.4 → 9.02020-02-20

PHP version history (4 changes)6.0PHP &gt;=7.0

5.0PHP &gt;=5.6

4.0PHP &gt;=5.4

7.0.1PHP &gt;=7.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/3a53f9e84b8af6f4e617504c176bae99b56220f35bffba0a499c9db100a3b43f?d=identicon)[czukowski](/maintainers/czukowski)

---

Top Contributors

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

---

Tags

databasemockphpunitsqlphpunitdatabasemock

### Embed Badge

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

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

###  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.

1718.0M353](/packages/php-mock-php-mock-phpunit)[blastcloud/guzzler

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

272408.6k29](/packages/blastcloud-guzzler)[elliotchance/concise

Concise is test framework for using plain English and minimal code, built on PHPUnit.

47223.6k3](/packages/elliotchance-concise)[mnapoli/phpunit-easymock

Helpers to build PHPUnit mocks

3875.9k5](/packages/mnapoli-phpunit-easymock)[box/shmock

Shorthand for (PHPUnit) Mocking

3430.8k1](/packages/box-shmock)[lastzero/test-tools

Increases testing productivity by adding a service container and self-initializing fakes to PHPUnit

2244.0k13](/packages/lastzero-test-tools)

PHPackages © 2026

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