I am reviewing the information in the MongoDB documentation regarding test design which is a good 'how' of implementing a test, but I am curious if anyone has any feedback or know of additional resources that elaborate on a cohesive strategy or template for how to pursue TDD when developing with one of these databases.

For a school project I want to adequately test a mongdb that is populated with a collection of entries like the following from a webapp:

  "_id" : 1234,
  "name" : "John",
  "coordinates" : [90.1,30.0],
  "text" : "A complete sentence would go here."

Right off the top I am seeing that generally what I want to do is have a mock database I can populate with test data for testing database operations (the webapp will add new entries and search for existing entries that match search criteria, I am not anticipating it to modify existing entries). However, lacking much experience with test driven development/mongo databases, I am curious to know if there are gaps in my strategy. For example, in addition to testing for correct execution of operations and assertions for validity of inputs, are there other unit tests I should formulate?


2 Answers 2


In general MongoDB fares well with a substitute database as there is no schema to reproduce on it. I tend to exercise the database in two categories of tests:

  • integration tests for the classes wrapping database usage, such as Data Access Objects or Repositories. I use the test database of the local machine, create as many collections objects as necessary and pass them in to the object under test. Most of the logic, like query correctness or validation, should be tested here.

  • end-to-end tests of the whole application where I use. I try to write these tests and their checks so that they do not depend on existing fixtures to be present, e.g. generating a random username and registering it for the duration of a single new test being run. These tests check that all parts of the application are wired together, that the correct host and port are configured, and so on.


Right off the top I am seeing that generally what I want to do is have a mock database I can populate with test data

Actually I would consider another option - using stubbing to remove the dependency altogether. You trust Mongo to do its operations, so stub them out. This can require some significant test redeisgn but if possible. For example, if you have a data store for zip codes with 50,000 entries, stub it out and use a few sample values as fixed values in tests. It will also make the tests more determinate and repeatable for passing / failing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.