Reputation: 10310
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.
Upvotes: 1
Views: 2893
Reputation: 46532
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:
DB
type that consumers can use for their unit tests without hitting MongoDB.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).Upvotes: 4