1

I am using the official Mongo driver for Go. My code looks like this (omitted error handling in order to make the example simpler):

type DB struct {
    collection *mongo.Collection
}

func (db DB) GetUsers() []*User {
    res, _ := db.collection.Find(context.TODO(), bson.M{})
    var users []*User
    res.All(context.TODO(), &users)
    return users
}

Question: How to unit test the GetUsers function?

I went through the driver's documentation and didn't find any testing related functionality/best practices.

Note: The full code is available on GitHub.

Sasha Shpota
  • 9,436
  • 14
  • 75
  • 148

1 Answers1

4

You can't unit test connectivity to a database, by definition - that would be an integration test. To my mind, this method is too simple to bother testing with a mock MongoDB; instead, the most value would probably be from a combination of:

  1. A mock DB type that consumers can use for their unit tests without hitting MongoDB.
  2. An integration test of the DB type itself, that hits a real test Mongo database - this could be a test database created and filled by the test suite, and destroyed after tests are completed (which would be my recommendation).
Adrian
  • 42,911
  • 6
  • 107
  • 99
  • Thank you. But I am interested particularly in **unit testing**. For instance, if you open the original code on GitHub, there is also an error handling logic which is better testable with unit tests. – Sasha Shpota Jan 24 '20 at 15:37
  • 1
    Then you'll have to mock the Mongo driver itself. – Adrian Jan 24 '20 at 15:39