How to mock mgo?

Open
#418 0 comments 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
20/100
Issue type
Documentation
Clarity
Needs clarification
Activity status
Stale
Tech stack
go
Domain
testing-qa

Research direction

The issue provides no repository file or test entry point; begin with the printIDs example and the Collection and Query interfaces around mgo.Collection and mgo.Query. The desired outcome is not specified beyond understanding nested mocks, so there is no defined completion condition.

Written by the indexing model from the issue text.

Description

pkg-mock question

I have a question which puzzles me quite a bit. Consider the below code snippet, which runs a query against the employee collection, and iterates over the result set and then prints the id of each employee:

func printIDs(c *mgo.Collection) {
  query := bson.M{...} // some random query

  q := collection.Find(query)
  iter := q.Iter()
  for iter.Next(&employee) {
    hex := employee.Id.Hex()
    fmt.Println("id is", hex)
  }
}

I know, that in order to be able to pass a mock collection object, I have to change the function signature to use an interface type:

func printIDs(c Collection) {
...
}

Since the printIDs function only uses the Find method on the *mgo.Collection, the new Collection interface will look like this:

type Collection interface {
  Find(query interface{}) *mgo.Query
}

But here is where my trouble begins: the printIDs function will use the query object returned from the Find method, therefore I want that returned object to be a mock as well. Just as before, I have to create an interface for *mgo.Query, so now I can use it like this:

c := &MockCollection{}
q := MockQuery{}
c.Mock.On("Find", mock.AnythingOfType("bson.M")).Return(q) // mock collection to return a mock query
printIDs(c)

But now, I have to change the Collection interface's Find method to return this new Query interface type instead of *mgo.Query, which will not work because now the *mgo.Collection is not implementing the Collection interface anymore.

Can anyone throw some light on how to mock this kind of nested structures?
With thanks,
Laszlo

Dominant language
Go
Stars
26.2k
Forks
1.9k
Avg merge
2d 4h
Merged PRs (30d)
2

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from stretchr/testify

All issues in stretchr/testify

Similar issues

More Go issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.