helmich / mongomock
Library containing highly intelligent MongoDB mocks for unit testing
Fund package maintenance!
martin-helmich
donate.helmich.me
Installs: 63 127
Dependents: 6
Suggesters: 0
Security: 0
Stars: 28
Watchers: 5
Forks: 22
Open Issues: 4
Requires
- php: ^7.1.0 || ^8.0
- ext-json: *
- ext-mongodb: *
- mongodb/mongodb: ^1.0
- phpunit/phpunit: >=6.0,<10.0
This package is auto-updated.
Last update: 2024-10-18 05:31:05 UTC
README
Author and license
Martin Helmich
This library is MIT-licenced.
Synopsis and motivation
This class contains implementations of the MongoDB\Collection and MongoDB\Database classes (not to be confused with the Mongo\Collection class from the deprecated mongo extension) that can store, modify and filter documents in memory, together with a set of (optional) PHPUnit assertions.
I wrote this library because I wanted to unit-test a library that used MongoDB
collections intensively and felt that mocking the MongoDB\Collection
class
using PHPUnit's built-in mock builders was too restrictive.
Note: Currently, this implementation contains only a subset of the actual MongoDB collection API. I've only implemented the parts of the API that I needed for my use case. If you need additional functionality, feel free to open an issue, or (better yet) a pull request.
Installation
$ composer require --dev helmich/mongomock
Compatibility
There are several release branches of this library, each of these being compatible with different releases of PHPUnit and PHP. The following table should give an easy overview:
When you are using composer require
and have already declared a dependency to phpunit/phpunit
in your composer.json
file, Composer should pick latest compatible version automatically.
Usage
You can use this library exactly as you'd use the MongoDB\Collection
or MongoDB\Database
classes
(in theory, at least -- remember, this package is not API-complete):
use Helmich\MongoMock\MockCollection; $collection = new MockCollection(); $collection->createIndex(['foo' => 1]); $documentId = $collection->insertOne(['foo' => 'bar'])->insertedId(); $collection->updateOne(['_id' => $documentId], ['$set' => ['foo' => 'baz']]);
Differences
In some aspects, the MongoDB\Collection
's API was extended to allow for better
testability:
-
Filter operands may contain callback functions that are applied to document properties:
$r = $collection->find([ 'someProperty' => function($p) { return $p == 'bar'; } ]);
-
Filter operands may contain PHPUnit constraints (meaning instances of the
PHPUnit_Framework_Constraint
class). You can easily build these using the factory functions in thePHPUnit_Framework_Assert
class.$r = $collection->find([ 'someProperty' => \PHPUnit_Framework_Assert::isInstanceOf(\MongoDB\BSON\Binary::class) ]);
Testing
To run the tests (anywhere with a running Docker installation):
$ docker-compose run php7phpunit
$ docker-compose run php8phpunit