Friday, 12 February 2016

Mongo Unit Testing - Fongo

Unit testing with any database can be a bit of a pain.  However, with Mongo it is really easy thanks to a testing framework called Fake Mongo (fongo).  The Fongo Client implements the MongoClient interface in memory so is perfect for unit testing.

https://github.com/fakemongo/fongo

Maven Dependency

    <dependency>
        <groupId>com.github.fakemongo</groupId>
        <artifactId>fongo</artifactId>
        <version>2.0.4</version>
<scope>test</scope>
    </dependency>

Example

Now just inject an instance of Fongo anywhere that a MongoClient would have been used.

    final Fongo fakeMongo = new Fongo("FakeMongo");
    final MongoClient mongoClient = fakeMongo.getMongo();

Now just interact with the mongoClient as normal.  Add documents, delete, read etc

No comments:

Post a comment